`

Log4j自定义Appender(二)

阅读更多

自定义Appender实际应用

 

场景一:利用log4j MongoDB插件 向 MongoDB数据库写入数据

 

1.项目引入 jar 包:spring-data-mongodb-log4j:1.8.0,及 log4j 1.2以上jar包

2.log4j.properties 配置

 

 

log4j.rootLogger=INFO, stdout

log4j.appender.stdout=org.springframework.data.mongodb.log4j.MongoLog4jAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
log4j.appender.stdout.host = localhost
log4j.appender.stdout.port = 27017
log4j.appender.stdout.database = logs
#log4j.appender.stdout.collectionPattern = %X{year}%X{month}
log4j.appender.stdout.collectionPattern = sys_logs
log4j.appender.stdout.applicationId = my.application
log4j.appender.stdout.warnOrHigherWriteConcern = FSYNC_SAFE

 

3.程序中应用

 

Logger log = Logger.getRootLogger();
log.info("I am ready.") ;

 

 

说明:

org.springframework.data.mongodb.log4j.MongoLog4jAppender

此类中通过

extends AppenderSkeleton

 

实现了自定义 Appender  如下:

 

package org.springframework.data.mongodb.log4j;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.WriteConcern;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.MDC;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;
public class MongoLog4jAppender extends AppenderSkeleton {
    public static final String LEVEL = "level";
    public static final String NAME = "name";
    public static final String APP_ID = "applicationId";
    public static final String TIMESTAMP = "timestamp";
    public static final String PROPERTIES = "properties";
    public static final String TRACEBACK = "traceback";
    public static final String MESSAGE = "message";
    public static final String YEAR = "year";
    public static final String MONTH = "month";
    public static final String DAY = "day";
    public static final String HOUR = "hour";
    protected String host = "localhost";
    protected int port = 27017;
    protected String database = "logs";
    protected String collectionPattern = "%c";
    protected PatternLayout collectionLayout;
    protected String applicationId;
    protected WriteConcern warnOrHigherWriteConcern;
    protected WriteConcern infoOrLowerWriteConcern;
    protected Mongo mongo;
    protected DB db;
    public MongoLog4jAppender() {
        this.collectionLayout = new PatternLayout(this.collectionPattern);
        this.applicationId = System.getProperty("APPLICATION_ID", (String)null);
        this.warnOrHigherWriteConcern = WriteConcern.SAFE;
        this.infoOrLowerWriteConcern = WriteConcern.NORMAL;
}

    public MongoLog4jAppender(boolean isActive) {
        super(isActive);
        this.collectionLayout = new PatternLayout(this.collectionPattern);
        this.applicationId = System.getProperty("APPLICATION_ID", (String)null);
        this.warnOrHigherWriteConcern = WriteConcern.SAFE;
        this.infoOrLowerWriteConcern = WriteConcern.NORMAL;
}

    public String getHost() {
        return this.host;
}

    public void setHost(String host) {
        this.host = host;
}

    public int getPort() {
        return this.port;
}

    public void setPort(int port) {
        this.port = port;
}

    public String getDatabase() {
        return this.database;
}

    public void setDatabase(String database) {
        this.database = database;
}

    public String getCollectionPattern() {
        return this.collectionPattern;
}

    public void setCollectionPattern(String collectionPattern) {
        this.collectionPattern = collectionPattern;
        this.collectionLayout = new PatternLayout(collectionPattern);
}

    public String getApplicationId() {
        return this.applicationId;
}

    public void setApplicationId(String applicationId) {
        this.applicationId = applicationId;
}

    public void setWarnOrHigherWriteConcern(String wc) {
        this.warnOrHigherWriteConcern = WriteConcern.valueOf(wc);
}

    public String getWarnOrHigherWriteConcern() {
        return this.warnOrHigherWriteConcern.toString();
}

    public String getInfoOrLowerWriteConcern() {
        return this.infoOrLowerWriteConcern.toString();
}

    public void setInfoOrLowerWriteConcern(String wc) {
        this.infoOrLowerWriteConcern = WriteConcern.valueOf(wc);
}

    protected void connectToMongo() throws UnknownHostException {
        this.mongo = new Mongo(this.host, this.port);
        this.db = this.mongo.getDB(this.database);
}

    protected void append(LoggingEvent event) {
        if(null == this.db) {
            try {
                this.connectToMongo();
} catch (UnknownHostException var9) {
                throw new RuntimeException(var9.getMessage(), var9);
}
        }

        BasicDBObject dbo = new BasicDBObject();
        if(null != this.applicationId) {
            dbo.put("applicationId", this.applicationId);
MDC.put("applicationId", this.applicationId);
}

        dbo.put("name", event.getLogger().getName());
dbo.put("level", event.getLevel().toString());
Calendar tstamp = Calendar.getInstance();
tstamp.setTimeInMillis(event.getTimeStamp());
dbo.put("timestamp", tstamp.getTime());
Map props = event.getProperties();
        if(null != props && props.size() > 0) {
            BasicDBObject traceback = new BasicDBObject();
Iterator now = props.entrySet().iterator();
            while(now.hasNext()) {
                Entry coll = (Entry)now.next();
traceback.put(coll.getKey().toString(), coll.getValue().toString());
}

            dbo.put("properties", traceback);
}

        String[] traceback1 = event.getThrowableStrRep();
        if(null != traceback1 && traceback1.length > 0) {
            BasicDBList now2 = new BasicDBList();
now2.addAll(Arrays.asList(traceback1));
dbo.put("traceback", now2);
}

        dbo.put("message", event.getRenderedMessage());
Calendar now1 = Calendar.getInstance();
MDC.put("year", Integer.valueOf(now1.get(1)));
MDC.put("month", String.format("%1$02d", new Object[]{Integer.valueOf(now1.get(2) + 1)}));
MDC.put("day", String.format("%1$02d", new Object[]{Integer.valueOf(now1.get(5))}));
MDC.put("hour", String.format("%1$02d", new Object[]{Integer.valueOf(now1.get(11))}));
String coll1 = this.collectionLayout.format(event);
MDC.remove("year");
MDC.remove("month");
MDC.remove("day");
MDC.remove("hour");
        if(null != this.applicationId) {
            MDC.remove("applicationId");
}

        WriteConcern wc;
        if(event.getLevel().isGreaterOrEqual(Level.WARN)) {
            wc = this.warnOrHigherWriteConcern;
} else {
            wc = this.infoOrLowerWriteConcern;
}

        this.db.getCollection(coll1).insert(dbo, wc);
}

    public void close() {
        if(this.mongo != null) {
            this.mongo.close();
}

    }

    public boolean requiresLayout() {
        return true;
}
}

 

场景二:项目中某项操作或执行记录,通过自定义Appender 写入文件或打印控制台等

 

1.log4j.properties 配置

 

 

log4j.logger.historyLog=INFO, history
log4j.additivity.historyLog= false
log4j.appender.history=com.xxx.HistoryLogAppender
log4j.appender.history.host = localhost
log4j.appender.history.port = 27017
log4j.appender.history.database = logs
log4j.appender.history.collectionPattern = %X{year}%X{month}
#log4j.appender.history.collectionPattern = sys_logs
log4j.appender.history.hs_name=hs_name

 其中 com.xxx.HistoryLogAppender 为项目中通过继承

 

 

extends AppenderSkeleton {

实现的 自定义 Appender

 

2.程序中应用

 

Logger cutsomLog = Logger.getLogger("historyLog");
cutsomLog.info("I am ready.");

 

 

分享到:
评论

相关推荐

    log4j日志驱动包

    #自定义Appender log4j.appender.im = net.cybercorlin.util.logger.appender.IMAppender log4j.appender.im.host = mail.cybercorlin.net log4j.appender.im.username = username log4j.appender.im.password = ...

    log4j自定义日志文件名及日志输出格式

    配置文件(log4j.properties)中,你需要将这个自定义的Appender和Layout加入: ```properties log4j.appender.customAppender=your.package.CustomLogAppender log4j.appender.customAppender.layout=your.package...

    log4j自定义

    《深入理解Log4j自定义》 在Java开发中,日志系统扮演着至关重要的角色,它能够帮助我们记录程序运行过程中的各种信息,便于调试、监控和问题排查。Log4j作为一款广泛使用的日志框架,其强大的可配置性和自定义能力...

    Log4J_全能配置文件.pdf

    - `log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender`:指定了名为`CONSOLE`的appender是控制台输出。 - `log4j.appender.CONSOLE.Target=System.out`:日志输出到标准输出流(System.out)。 - `log4j....

    log4j输出多个自定义路径的日志文件小例子

    要实现输出多个自定义路径的日志文件,我们需要在Log4j的配置文件(通常是`log4j.properties`或`log4j.xml`)中定义多个Appender。Appender是Log4j中负责将日志信息输出到指定目的地的组件,例如文件、控制台、网络...

    (转)如何自建appender扩展Log4j框架

    5. **注册Appender**:在Log4j的配置文件(如log4j.properties或log4j.xml)中,声明你的自定义Appender,并配置相关属性。例如: ```xml &lt;appender name="MyCustomAppender" class=...

    Log4net自定义信息(变量或属性或字段)存入数据库

    本主题聚焦于如何利用Log4net将自定义信息,如变量、属性或字段,存储到数据库中,这对于监控应用状态、分析错误和追踪性能异常至关重要。 首先,Log4net提供了一个灵活的配置机制,允许开发者通过XML配置文件或...

    Log4jToWriterAppender.zip

    log4j.appender.stdout=org.apache.log4j.WriterAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern...

    SpringBoot框架配置log4j和log4j2的配置代码

    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n log4j.appender.file=org.apache.log4j....

    log4j-1.2.17.jar下载

    四、使用Log4j进行日志记录 在Java代码中,我们通过创建Logger实例来记录日志。例如: ```java import org.apache.log4j.Logger; public class MyClass { private static final Logger logger = Logger....

    log4j多文件输出打印

    log4j.appender.ERROR.layout=org.apache.log4j.PatternLayout log4j.appender.ERROR.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n # 定义一个名为INFO的Appender,用于记录信息级别及以上的日志 ...

    log4j_jar包跟教程说明

    5. **自定义Appender和Layout** - Log4j允许开发者创建自定义的Appender和Layout来满足特定需求,如发送邮件、写入数据库等。 - Appender决定了日志信息的输出位置,而Layout则决定日志的显示格式。 6. **Log4j的...

    Spring项目中怎么配置log4j

    log4j.appender.R=org.apache.log4j.DailyRollingFileAppender log4j.appender.R.File=./logs/app.log log4j.appender.R.ImmediateFlush=true log4j.appender.R.Append=true log4j.appender.R.Threshold=DEBUG ...

    log4j-1.2.17的jar包以及依赖包,还有一份log4j的配置文件,输出到控制台和文件夹两种配置

    **二、Log4j配置文件** 在压缩包中,还包含了一份名为`log4j.properties`的配置文件。这是Log4j使用的一种配置格式,基于Java Properties格式。配置文件决定了日志信息如何输出、输出到哪里,以及日志的级别等关键...

    log4j-1.2.17.jar及配置文件

    二、log4j-1.2.17.jar文件 这个jar文件包含了Log4j 1.2.17的所有类和资源,是使用Log4j的基础。在Java应用程序中,我们通常会将log4j-1.2.17.jar添加到项目的类路径中,以便调用其API进行日志记录。例如,通过以下...

    log4j jarjar包

    二、Log4j核心组件 1. **Logger**:日志器是Log4j的基本组件,负责接收日志事件并将其传递给适当的输出。开发者可以根据需要创建多个日志器,每个日志器可以有不同的输出配置。 2. **Appender**:Appender负责将...

    tomcat下的log4j日志配置

    2. **编写初始化 Servlet**:创建一个自定义的 Servlet 来初始化 Log4j。该 Servlet 的主要任务是在启动时加载特定的 `log4j.properties` 文件。 ```java public class Log4jInitServlet extends HttpServlet { ...

    如何在Java工程中使用Log4j

    log4j.appender.fileLogger=org.apache.log4j.RollingFileAppender log4j.appender.fileLogger.File=D:\\log.log log4j.appender.fileLogger.MaxFileSize=10MB log4j.appender.fileLogger.MaxBackupIndex=100 log4j....

    log4j与log4j.properties的配置.doc

    这些级别可以自定义,但 Log4j 建议只使用四个级别:ERROR、WARN、INFO 和 DEBUG。 四、Appenders Appenders 是 Log4j 的输出目的地,用于将日志信息输出到不同的目的地。Log4j 提供了多种 Appenders,包括: 1. ...

    Log4j 把不同包的日志打印到不同位置

    log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n # 创建module1的Logger,关联Appender R log4j.logger....

Global site tag (gtag.js) - Google Analytics