开发者

Get the current layout from an Appender in Logback?

开发者 https://www.devze.com 2023-03-15 12:16 出处:网络
Consider the following basic configuration for logback: <configuration> <appender name=\"ControlAppender\" class=\"org.quackbot.ControlAppender\">

Consider the following basic configuration for logback:

<configuration>
    <appender name="ControlAppender" class="org.quackbot.ControlAppender">
        <pattern>%d{MM/dd/yyy hh:mm:ss a}  %-5p %c - </pattern>
    </appender>
</configuration>开发者_如何学Go;

How can I use that layout and format the line? A few different blog posts and mailing lists said that at one time AppenderBase had a getLayout() and setLayout() method, but they have sense been removed.

Reimplementing the getters and setters for the layout in my code don't work, it just returns null. event.getFormattedMessage() returns the original line, not the formatted one. I can't seem to find any other method that would format the message according to the layout.

Is there any way to format a message according to the pattern specified in the configuration?


Logback configuration just pieces together the elements that you specify. It does not make up components on its own. In the config file above, you have not specified a layout element and as such it won't get injected to your ControlAppender.

Since I don't know what ControlAppender does I can't suggest the most appropriate solution. However, you have at least two options:

1) Have ControlAppender accept a layout as a parameter. Your config file would look similar to:

<configuration>
    <appender name="ControlAppender" class="org.quackbot.ControlAppender">
        <layout class="class="ch.qos.logback.classic.PatternLayout"">
          <pattern>%d{MM/dd/yyy hh:mm:ss a}  %-5p %c - </pattern>
        </layout>
    </appender>
</configuration>

Logback would inject a PatternLayout instance into ControlAppender. You could then use the PatternLayout instance to format events according the pattern of your choice.

2) If you are always going to use a PatternLayout, you could create it directly from the pattern. Your config file would look similar to:

<configuration>
    <appender name="ControlAppender" class="org.quackbot.ControlAppender">
      <pattern>%d{MM/dd/yyy hh:mm:ss a}  %-5p %c - </pattern>
    </appender>
</configuration>

You would need a setter method in ControlAppender, i.e. setPattern, to have the pattern injected into ControlAppender. Once you have the pattern, you could create a PatternLayout on your own. For example by invoking:

 PatternLayout pl = new PatternLayout();
 pl.setPattern(pattern);
 pl.setContext(context);
 pl.start();

Shout on the logback users list if you need further assistance.

0

精彩评论

暂无评论...
验证码 换一张
取 消