1 /*
2 * Copyright 2008-2019 by Emeric Vernat
3 *
4 * This file is part of Java Melody.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package net.bull.javamelody;
19
20 import org.apache.log4j.AppenderSkeleton;
21 import org.apache.log4j.Level;
22 import org.apache.log4j.Logger;
23 import org.apache.log4j.PatternLayout;
24 import org.apache.log4j.spi.LoggingEvent;
25
26 /**
27 * Appender pour les logs de log4j, configuré automatiquement par {@link MonitoringFilter}.
28 * @author Emeric Vernat
29 */
30 public class Log4JAppender extends AppenderSkeleton {
31 private static final String MESSAGE_PATTERN = "%-5p [%c] %m%n";
32 private static final Level THRESHOLD = Level.WARN;
33
34 private static final Log4JAppender SINGLETON = new Log4JAppender();
35
36 /**
37 * Constructeur.
38 */
39 public Log4JAppender() {
40 super();
41 setLayout(new PatternLayout(MESSAGE_PATTERN));
42 setThreshold(THRESHOLD);
43 setName(getClass().getName());
44 }
45
46 static Log4JAppender getSingleton() {
47 return SINGLETON;
48 }
49
50 void register() {
51 Logger.getRootLogger().addAppender(this);
52 }
53
54 void deregister() {
55 Logger.getRootLogger().removeAppender(this);
56 }
57
58 /**
59 * {@inheritDoc}
60 */
61 @Override
62 protected void append(LoggingEvent event) {
63 final Throwable throwable;
64 if (event.getThrowableInformation() == null) {
65 throwable = null;
66 } else {
67 throwable = event.getThrowableInformation().getThrowable();
68 }
69 LoggingHandler.addErrorLogToCounter(getLayout().format(event), throwable);
70 }
71
72 /**
73 * {@inheritDoc}
74 */
75 @Override
76 public void close() {
77 // rien à faire
78 }
79
80 /**
81 * {@inheritDoc}
82 */
83 @Override
84 public boolean requiresLayout() {
85 return false;
86 }
87 }
88