cn.jiangzeyin.common.DefaultSystemLog Maven / Gradle / Ivy
package cn.jiangzeyin.common;
import ch.qos.logback.classic.*;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy;
import ch.qos.logback.core.util.FileSize;
import cn.jiangzeyin.common.spring.SpringUtil;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author jiangzeyin
* Created by jiangzeyin on 2017/2/3.
*/
public class DefaultSystemLog {
private static final LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
private static final Map LOG_TYPE_LOGGER_MAP = new ConcurrentHashMap<>();
private static final String TYPE_ERROR_TAG = "ERROR";
private static ConsoleAppender consoleAppender;
public enum LogType {
REQUEST, REQUEST_ERROR,
DEFAULT, ERROR
}
public static void init() {
consoleAppender = initConsole();
initSystemLog();
}
/**
* 加载系统日志文件对象
*/
private static void initSystemLog() {
for (LogType type : LogType.values()) {
String tag = type.toString();
Level level = Level.INFO;
if (tag.endsWith(TYPE_ERROR_TAG)) {
level = Level.ERROR;
}
Logger logger = initLogger(tag, tag, level);
LOG_TYPE_LOGGER_MAP.put(type, logger);
}
}
/**
* 加载控制显示
*
* @return r
*/
private static ConsoleAppender initConsole() {
ConsoleAppender appender = new ConsoleAppender<>();
PatternLayout patternLayout = new PatternLayout();
patternLayout.setContext(loggerContext);
patternLayout.setPattern("%date %level [%thread] %logger{10} [%file:%line]- x:\\(%X\\) %msg%n");
patternLayout.start();
appender.setLayout(patternLayout);
appender.setContext(loggerContext);
appender.start();
return appender;
}
/**
* 创建日志对象
*
* @param tag tag
* @param path path
* @param level lv
* @return logger
*/
private static Logger initLogger(String tag, String path, Level level) {
Logger logger = (Logger) LoggerFactory.getLogger(tag);
logger.detachAndStopAllAppenders();
logger.setLevel(level);
AsyncAppender asyncAppender = new AsyncAppender();
asyncAppender.setDiscardingThreshold(0);
asyncAppender.setQueueSize(512);
//define appender
RollingFileAppender appender = new RollingFileAppender<>();
//policy
SizeAndTimeBasedRollingPolicy