一般情况下elk,日志会通过logstash写入es,本文主要记录轻量级项目直接利用logback-elasticsearch-appender写入es。
1、添加maven依赖
<!-- elasticsearch -->
<dependency>
<groupId>com.internetitem</groupId>
<artifactId>logback-elasticsearch-appender</artifactId>
<version>1.6</version>
</dependency>
2、编辑resources目录下的日志配置文件,logback.xml
<!-- es相关配置1 -->
<appender name="ELASTIC" class="com.internetitem.logback.elasticsearch.ElasticsearchAppender">
<url>http://账号:密码@ip地址:端口/_bulk</url>
<index>log-此处为日志规则-%d{yyyy-MM-dd}</index>
<loggerName>es-logger</loggerName>
<errorLoggerName>es-error-logger</errorLoggerName>
<authentication class="com.internetitem.logback.elasticsearch.config.BasicAuthentication"/> <!-- es开启认证时使用-->
<properties>
<property>
<name>host</name>
<value>${HOSTNAME}</value>
<allowEmpty>false</allowEmpty>
</property>
<property>
<name>severity</name>
<value>%level</value>
</property>
<property>
<name>thread</name>
<value>%thread</value>
</property>
<property>
<name>stacktrace</name>
<value>%ex</value>
</property>
<property>
<name>logger</name>
<value>%logger</value>
</property>
</properties>
<headers>
<header>
<name>Content-Type</name>
<value>application/json</value>
</header>
</headers>
</appender>
<root additivity="true" level="INFO">
<!-- es相关配置2 -->
<appender-ref ref="ELASTIC"/>
</root>
<!-- es相关配置3 -->
<logger name="es-error-logger" level="ERROR" additivity="false">
<appender-ref ref="NGH_ERROR"/>
</logger>
<!-- es相关配置4 -->
<logger name="es-logger" level="DEBUG" additivity="false">
<appender name="ES_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>%msg
</pattern>
</encoder>
</appender>
</logger>
<appender name="NGH_ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<Append>true</Append>
<prudent>false</prudent>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd/HH:mm:ss.SSS}|%X{localIp}|%X{requestId}|%X{requestSeq}|^_^|[%t] %-5level %logger{50} %line - %m%n</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/ngh-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxFileSize>256MB</maxFileSize>
<maxHistory>15</maxHistory>
<totalSizeCap>32GB</totalSizeCap>
</rollingPolicy>
</appender>
3、在application.yml中设定日志level
logging:
level:
root: info
另外我们也可以在root部分不适用es记录日志而在需要的代码中用如下方式记录日志
/**
* 例子
*/
@RestController
@RequestMapping("log")
public class EsLoggerController {
private Logger logger = LoggerFactory.getLogger("es-logger");
@GetMapping("log")
public ApiResult<String> log()
{
logger.warn ("eslogger");
return ApiResult.success ("done!");
}
}
暂无评论...