封装自己的LogUtils —— 基于Logback&Slf4j

前言

统一、简介的日志输出工具类,欢迎大家给出更好的方案。

正文

LogUtils.java

package com.hyperdai.contest.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * author hyperdai
 * create 2019-05-24 21:26
 */
public class LogUtils {

    private static final Logger wechatCpFailLog = LoggerFactory
            .getLogger("com.hyperdai.dai.service.Ac.impl.WechatCpServiceImpl");

    private static final Logger worksServiceFailLog = LoggerFactory
            .getLogger("com.hyperdai.dai.service.Ac.impl.service.WorksServiceImpl");


    public static final Logger commonLog = LoggerFactory.getLogger(LogUtils.class);

    public static void logWechatError(String errMsg, Exception e) {
        loggerToFileAndAlert(wechatCpFailLog, errMsg, e);
    }

    public static void logWorksError(String errMsg, Exception e) {
        loggerToFileAndAlert(worksServiceFailLog, errMsg, e);
    }

    public static void log(String errMsg, Exception e) {
        loggerToFileAndAlert(commonLog, errMsg, e);
    }

    public static void loggerToFileAndAlert(Logger logger, String errMsg, Exception e) {
        if (e != null) {
            logger.error("errMsg = {}, e = ", errMsg, e);
            if (logger != commonLog) {
                commonLog.error("errMsg = {}, e = ", errMsg, e);
            }
        } else {
            logger.error("errMsg = {}", errMsg);
            if (logger != commonLog) {
                commonLog.error("errMsg = {}", errMsg);
            }
        }
    }
}

logback.xml



    

    

    
        
        
            ${CONSOLE_LOG_PATTERN}
        
    

    
        ${user.dir}/log/customer_service_es.log
        
            ${user.dir}/log/log-%d{yyyy-MM-dd}.gz
            90
        
        
            ${FILE_LOG_PATTERN}
            UTF-8
        
    

    
        ${user.dir}/log/push_account_to_es_fail.log
        
            ${user.dir}/log/works_service_fail-log-%d{yyyy-MM-dd}.gz
            15
        
        
            ${FILE_LOG_PATTERN}
            UTF-8
        
    

    
        ${user.dir}/log/push_customer_to_es_fail.log
        
            ${user.dir}/log/wechat_service_fail-log-%d{yyyy-MM-dd}.gz
            15
        
        
            ${FILE_LOG_PATTERN}
            UTF-8
        
    










    
        
    

    
        
    

    
        
        
    

    
    
        
            
            
        
        
            
            
        
    

    
    
        
            
        
        
            
        
    

你可能感兴趣的:(Java)