1

我想Logback在 Grails 中用作我的日志记录框架。因此,我将所有东西都设置好了,但我的实现在配置文件本身上失败了。正如我猜想的那样,原因是在 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_DIRBACKUP_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
  }
}

我在这里做错了什么?

4

1 回答 1

3

天啊!经过搜索和大量试验/错误后,我找到了解决方案,它非常接近,现在看起来很明显:我必须用 声明这两个变量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 重新扫描这个文件时创建的临时日志文件......

于 2013-02-25T14:11:04.433 回答