我想在Grails中使用Logback
作为我的日志记录框架。因此我设置了所有工作,但我的实现在配置文件本身上失败了。原因是,正如我猜的那样,在Groovy Script的范围内,但我无法弄明白......
如果我定义我的String
属性而没有任何我想要在以后使用的标识符,我会收到一条警告,说明它可能无法访问。例如:
LOG_DIR = 'c:/temp/myproject/logs/'
BACKUP_DIR = LOG_DIR + 'backup/'
appender('F_MAIN', RollingFileAppender) {
file = LOG_DIR + 'test.log'
rollingPolicy(FixedWindowRollingPolicy) {
fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
// .... and so on
}
}
我从Logback收到以下错误消息,我非常确定无法联系到LOG_DIR
和BACKUP_DIR
:
13:33:32,036 |-ERROR in ch.qos.logback.classic.gaffer.AppenderDelegate@6fd00b - Appender [F_MAIN] of type [ch.qos.logback.core.rolling.RollingFileAppender] has no appplicable [LOG_DIR] property
13:33:32,068 |-ERROR in ch.qos.logback.classic.gaffer.ComponentDelegate@788ac3 - Component of type [ch.qos.logback.core.rolling.FixedWindowRollingPolicy] has no appplicable [BACKUP_DIR] property
我还通过使用@Field
标记声明这两个变量来尝试以下方法,但它仍然不起作用:
@Field String LOG_DIR = 'c:/temp/myproject/logs/'
@Field String BACKUP_DIR = LOG_DIR + 'backup/'
appender('F_MAIN', RollingFileAppender) {
file = LOG_DIR + 'test.log'
rollingPolicy(FixedWindowRollingPolicy) {
fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
// .... and so on
}
}
我在这里做错了什么?
答案 0 :(得分:2)
def
声明这两个变量,所以现在它们在整个脚本中都可见;)
例如,这是工作代码:
def LOG_DIR = 'c:/temp/myproject/logs/'
def BACKUP_DIR = LOG_DIR + 'backup/'
appender('F_MAIN', RollingFileAppender) {
file = LOG_DIR + 'test.log'
rollingPolicy(FixedWindowRollingPolicy) {
fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
// .... and so on
}
}
现在,我也可以在我的脚本中使用这样的函数:
def createFilename(String directory, String name, boolean isBackupFile) {
String filename = ''
if(isBackupFile) {
filename = "${directory}backup/MyProject-${name}.%d{yyyy-MM-dd}.%i.log.zip"
} else {
filename = "${directory}MyProject-${name}.log"
}
return filename
}
def fileAppenderLog = createFilename(LOG_DIR, 'output', false)
def fileAppenderLogBackup = createFilename(LOG_DIR, 'output', true)
appender('F_MAIN', RollingFileAppender) {
file = fileAppenderLog
rollingPoliciy(FixedWindowRollingPolicy) {
fileNamePattern = fileAppenderLogBackup
// .... and so on
}
}
这非常有用,我认为:),特别是如果你想声明一堆不同的日志文件,即使你想声明在Logback重新扫描这个文件时创建的临时日志文件......