1、第一种方式使用logback配<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false"> <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径--> <property name="LOG_HOME" value="./logs" /> <!-- 控制台输出 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符--> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg %n</pattern> </encoder> </appender> <appender name="logstash" class="net.logstash.logback.appender.LogstashTcpSocketAppender"> <param name="Encoding" value="UTF-8"/> <destination>10.0.0.43:9000</destination> <encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder" > <customFields>{"appname":"elkDemo"}</customFields> </encoder> </appender> <!-- 日志输出级别 --> <root level="INFO"> <appender-ref ref="STDOUT" /> <appender-ref ref="logstash" /> </root> </configuration>
2、第二种使用log4j2
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Properties> <Property name="LOG_FILE">api.log</Property> <Property name="Logstash">%Logstash</Property> <Property name="PID">????</Property> <Property name="LOG_EXCEPTION_CONVERSION_WORD">%xwEx</Property> <Property name="LOG_LEVEL_PATTERN">%5p</Property> <Property name="CONSOLE_LOG_PATTERN">%clr{%d{yyyy-MM-dd HH:mm:ss.SSS}}{faint} %clr{${LOG_LEVEL_PATTERN}} %clr{${sys:PID}}{magenta} %clr{--}{faint} %clr{[%15.15t]}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint}%4L %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property> <Property name="FILE_LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN} ${sys:PID} -- [%t] %-40.40c{1.} %4L: %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property> </Properties> <Appenders> <Console name="Console" target="SYSTEM_OUT" follow="true" > <PatternLayout charset="utf-8" pattern="${sys:CONSOLE_LOG_PATTERN}" /> </Console> <RollingFile name="File" fileName="${sys:LOG_FILE}" filePattern="logs/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH}-%i.log.gz"> <PatternLayout> <Pattern>${sys:FILE_LOG_PATTERN}</Pattern> <charset>utf-8</charset> </PatternLayout> <Policies> <SizeBasedTriggeringPolicy size="10 MB" /> </Policies> </RollingFile> <Socket name="Logstash" host="10.0.0.43" port="9000"> <JsonLayout compact="true" eventEol="true" /> </Socket> </Appenders> <Loggers> <Logger name="org.apache.catalina.startup.DigesterFactory" level="error" /> <Root level="info" includeLocation="true"> <AppenderRef ref="Console" /> <AppenderRef ref="Logstash"/> </Root> </Loggers> </Configuration>
<!-- log4j2 AsyncLogger need disruptor-->
<dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>3.4.2</version> </dependency>
<AsyncLogger name="com.xinyartech" level="info" includeLocation="true" > <appender-ref ref="logstash-tcp" /> </AsyncLogger>