由于Log4j中的默认行为,避免多次记录同一消息

时间:2014-09-19 14:04:12

标签: java grails logging log4j

我正在使用Grails应用程序,并希望将消息记录在不同的文件中。我想在不同的文件中记录异常,普通和API日志。但根据Log4j的一般角色,如果我们将记录器级别设置为' Info'然后警告和错误消息也将开始记录此文件,而我想在不同的文件中记录错误消息。因此,我的错误消息将在错误文件和信息文件中两次记录。虽然我想要那个'信息'记录器日志只是'信息'级别消息不是'错误'等级消息。并且'错误'记录器只记录错误消息。

以下是我的Log4j配置:

log4j = {
def layoutPattern = new PatternLayout("[%d{ISO8601}] %m \r\n")
def dailyRollingInfoFile = new DailyRollingFileAppender(
        name:"rollingInfoFileAppender",
        layout: layoutPattern,
        //Path of the Log File
        fileName:"C:\\MS-Logs\\Application\\MSLogs.log",
        datePattern: "'.'dd-MM-yyyy")

def dailyRollingExceptionFile = new DailyRollingFileAppender(
        name:"rollingExceptionFileAppender",
        layout: layoutPattern,
        //Path of the Log File
        fileName:"C:\\MS-Logs\\Exceptions\\ExceptionLogs.log",
        datePattern: "'.'dd-MM-yyyy")

def dailyRollingExceptionAPIFile = new DailyRollingFileAppender(
        name:"rollingAPIFileAppender",
        layout: layoutPattern,
        //Path of the Log File
        fileName:"C:\\MS-Logs\\API\\MS-NotificationsLogs.log",
        datePattern: "'.'dd-MM-yyyy")

 //For logging exceptions stack trace
appenders {
    appender dailyRollingInfoFile
    appender dailyRollingExceptionFile
    appender dailyRollingExceptionAPIFile
   }

root {
    info  'rollingInfoFileAppender', additivity: false
    debug 'rollingAPIFileAppender', additivity: false
    error 'rollingExceptionFileAppender'
}
}

现在,这是我添加过滤器的方式:

dailyRollingExceptionFile.addFilter(new org.apache.log4j.varia.LevelMatchFilter(levelToMatch:'ERROR', acceptOnMatch: true))
dailyRollingExceptionFile.addFilter(new org.apache.log4j.varia.DenyAllFilter())

//To make it sure that It will just Log, Messages by Info Logger
dailyRollingInfoFile.addFilter(new org.apache.log4j.varia.LevelMatchFilter(levelToMatch:'INFO', acceptOnMatch: true))
dailyRollingInfoFile.addFilter(new org.apache.log4j.varia.DenyAllFilter())

//To make it sure that It will just Log, Messages by API Logger
dailyRollingAPIFile.addFilter(new org.apache.log4j.varia.LevelMatchFilter(levelToMatch:'DEBUG', acceptOnMatch: true))
dailyRollingAPIFile.addFilter(new org.apache.log4j.varia.DenyAllFilter())

如何,可以避免在不同文件中两次记录相同的消息?如何在不在其他文件中重复的情况下将消息记录在不同的文件中?

感谢您的时间:)

1 个答案:

答案 0 :(得分:1)

我相信Log4j的LevelMatchFilter允许你做你想做的事情:

def dailyRollingInfoFile = new DailyRollingFileAppender(...)
dailyRollingInfoFile.addFilter(new org.apache.log4j.varia.LevelMatchFilter(levelToMatch:'INFO', acceptOnMatch: true))
dailyRollingInfoFile.addFilter(new org.apache.log4j.varia.DenyAllFilter())

DenyAllFilter删除了LevelMatchFilter不匹配的消息(即除了级别信息之外的所有内容)