如何在logback.xml中的appender中设置文件路径

时间:2013-05-29 09:51:09

标签: java filepath logback appender

我希望在logback.xml中的appender中设置文件路径(以及文件名) 我需要使用哪个类。请帮忙。以下是我的追加者

<appender name="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender">
    <discriminator class="com.hotwaxmedia.logger.ThreadNameBasedDiscriminator"/>
    <sift>
        <appender class="ch.qos.logback.core.FileAppender">
            <file>runtime/logs/app-${threadName}.html</file>
            <layout class="ch.qos.logback.classic.PatternLayout">
                <pattern>%p %d ${threadName} [%logger{0} : %-5level] %msg%n%rEx</pattern>
            </layout>
        </appender>
    </sift>
</appender>

3 个答案:

答案 0 :(得分:0)

您可以以编程方式加载appender

LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();
for (Logger logger : context.getLoggerList()) {
  for (Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders();     index.hasNext();) {
     Appender<ILoggingEvent> appender = index.next();
  }
}

然后您可以验证appenderFileAppender并且调用getFile()。请查看文档http://logback.qos.ch/apidocs/ch/qos/logback/core/FileAppender.html

答案 1 :(得分:0)

此问题与LOGBACK-833有关,已在logback版本1.0.12中修复。因此,您需要升级到logback版本1.0.12或更高版本。鉴别器实例必须将“threadName”定义为导出的键。否则,无法解析$ {threadName}。这是修改过的鉴别器:

<discriminator class="com.hotwaxmedia.logger.ThreadNameBasedDiscriminator">
  <!-- the key to export needs to be defined -->
  <key>threadName</key>
</discriminator>

答案 2 :(得分:0)

您必须在“fileNamePattern”标记中使用路径,例如:

    <Discriminator>

        <Key>userId</Key>

        <DefaultValue>general</DefaultValue>

    </Discriminator>



    <sift>

        <appender name="FILE-MODULENAME-${userId}" class="ch.qos.logback.core.rolling.RollingFileAppender">

                <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                  <!-- rollover daily -->
                  <fileNamePattern>/opt/webligic12/user_projects/domains/myDomain/servers/AdminServer/logs/%d{yyyy-MM-dd}/byUser/modulename/${userId}-%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
                  <timeBasedFileNamingAndTriggeringPolicy
                        class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <!-- or whenever the file size reaches maxFileSize -->
                    <maxFileSize>2MG</maxFileSize>
                  </timeBasedFileNamingAndTriggeringPolicy>
                </rollingPolicy>


            <Append>true</Append>

            <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">

                <Pattern>%d %X{user} %level %msg %n</Pattern>

            </encoder>

        </appender>

    </sift>

</appender>