• JsonLayout log4j2 json格式输出日志


    如果日志输出时,想改变日志的输出形式为Json格式,可以在log4j2.xml中使用JsonLayout标签,使日志输出格式为Json格式。

    前提需要Jackson的包,保证项目中包含jackson的依赖

    然后在log4j2.xml中在需要日志输出的地方,添加

    <JsonLayout/>

    例如需要在控制台输出格式为Json格式则:

     <!--这个输出控制台的配置-->
            <Console name="Console" target="SYSTEM_OUT">  
                <JsonLayout/>
            </Console>  

    如果需要在日志文件输出,则为:

             <RollingFile name="syswareLog" fileName="${LOG_HOME}/logs/sysware.log"
                         filePattern="${LOG_HOME}/logs/$${date:yyyy-MM}/sysware-%d{yyyy-MM-dd}-%i.log">
                <JsonLayout/>
                <Policies>
                    <TimeBasedTriggeringPolicy/>
                    <SizeBasedTriggeringPolicy size="100000 kb"/>
                </Policies>
                <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
                <DefaultRolloverStrategy max="100"/>
            </RollingFile>

    设置完成之后,日志输出格式如下:

    {
      "timeMillis" : 1547108632526,
      "thread" : "main",
      "level" : "WARN",
      "loggerName" : "com.ctrip.framework.apollo.internals.DefaultMetaServerProvider",
      "message" : "Could not find meta server address, because it is not available in neither (1) JVM system property 'apollo.meta', (2) OS env variable 'APOLLO_META' (3) property 'apollo.meta' from server.properties nor (4) property 'apollo.meta' from app.properties",
      "endOfBatch" : false,
      "loggerFqcn" : "org.apache.logging.slf4j.Log4jLogger",
      "threadId" : 1,
      "threadPriority" : 5
    }

    但是这个日志是格式化后的json,有同事提出需求,想让一个json对象输出为一行,这样日志读取的时候,可以以一个对象为单位读取,而不是一行。

    继续查看JsonLayout 源码,既然他提供了转换为json,那是不是也可以提供格式化json规则。

    org.apache.logging.log4j.core.layout.JsonLayout 。 继承自 AbstractJacksonLayout,在AbstractJacksonLayout 中有下面几个属性介绍。我们下面主要介绍这几个属性的含义及使用方法。

        protected final String eventEol;
        protected final ObjectWriter objectWriter;
        protected final boolean compact;
        protected final boolean complete;
    compact 设置是否紧凑输出,默认是false,如果设置为true,则不是用行位和缩进,大概意思是说,输出把所有的日志输出为一行。
         原文( If "true", does not use end-of-lines and indentation, defaults to "false".
    complete 设置是否完成,默认是false, 如果设置为true,则在日志开始和结束会包含页眉和页脚,和逗号。
        原文(If "true", includes the JSON header and footer, and comma between records.)
    eventEol 如果为“true”,则在每个日志事件后强制执行EOL(即使compact是“true”),默认是false,即使在紧凑模式下,也会生效,大概意思就是说,
         即使是在紧凑模式下,如果evetEol设置为true ,也会在每个log event(log.info().log.error(),log.debug()等等)之后强制换行输出。
    objectWriter 暂不清楚

    通过上面的属性介绍,根据需要,只需将compact ,evetEol 设置成true,即可将每行日志输出成一行json。
  • 相关阅读:
    数据库的单表查询Ⅰ
    数据库的基本操作Ⅲ
    数据库基本操作Ⅱ
    数据库的基本操作Ⅰ
    MYSQL的三种安装方式
    操作系统学期小结二
    操作系统学期小结一
    MAP接口课堂练习
    关于list接口和set接口的示例应用
    课堂作业整理三 (集合:list接口)
  • 原文地址:https://www.cnblogs.com/wenq001/p/10251634.html
Copyright © 2020-2023  润新知