How to hide the output of a single Logback logger? - java

I use logback in the following case
package ninja.template;
public class TemplateEngineManagerImpl implements TemplateEngineManager {
private final Logger logger = LoggerFactory.getLogger(TemplateEngineManagerImpl.class);
...
logger.info("Registered response template engines");
...
and I want to hide all the INFO output of this TemplateEngineManagerImpl class (or all the output - the class only logs at INFO level) but this class only.
Unfortunately, the following configuration doesn't work as I can still see "Registered response template engines" in my console output.
<configuration>
<appender name="STDOUT_TERSE" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern> | %msg%n</pattern>
</encoder>
</appender>
<logger name="ninja.template.TemplateEngineManagerImpl" level="OFF"/>
<root level="info">
<appender-ref ref="STDOUT_TERSE" />
</root>
</configuration>
note I tried also the following without results
<logger name="ninja.template.TemplateEngineManagerImpl" level="WARN"/>
and
<logger name="ninja.template" level="WARN"/>
and
<logger name="TemplateEngineManagerImpl" level="WARN"/>

The provided logback configuration works
<logger name="ninja.bodyparser.BodyParserEngineManagerImpl" level="WARN" additive="false"/>
The error I had that the string was logged in two different places.
So by displaying the full logger name with the following configuration:
<appender name="STDOUT_TERSE" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern> | %logger | %msg%n</pattern>
</encoder>
I was able to copy and paste the string that should be used as the logger name!

Related

Logback NOT writing in log.txt

Problem Statement: Logback is printing in console properly but not in log.txt file. There are many solutions given in other pages but apparently none worked. Could someone help me in this regard?
Java:-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Log {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger("Example App");
logger.info("'sup? I'm your info logger");
logger.debug("hey HEY hey! I'm your debug logger");
}
}
Config:- logback-fileAppender.xml
<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${project.basedir}/Log.txt</file>
<append>true</append>
<!-- set immediateFlush to false for much higher logging throughput -->
<immediateFlush>true</immediateFlush>
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration>
Expected:- The logs should be printed in log.txt
Actual:- The logs is not printed in log.txt
Note: I am using my customized directory structure in maven not the default provided by maven "src/main/resources".

How to include mdc key when logging exception using Logstash encoder

I have logback-spring.xml file where I have json console appender:
I include mdc key requestId:
however, this requestId is lost when there is a runtime exception being logged.
is there a way I can have the requestId printed in the logs when there is an exception?
<configuration>
<appender name="jsonConsoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<fieldNames>
<timestamp>log_datetime</timestamp>
<thread>thread</thread>
<logger>[ignore]</logger>
<version>[ignore]</version>
<levelValue>[ignore]</levelValue>
<callerClass>class_name</callerClass>
<callerMethod>method_name</callerMethod>
<callerFile>[ignore]</callerFile>
<callerLine>line_num</callerLine>
</fieldNames>
<includeMdcKeyName>requestId</includeMdcKeyName>
<timestampPattern>yyyy-MM-dd HH:mm:ss.SSS</timestampPattern>
<includeCallerData>true</includeCallerData>
<throwableConverter class="net.logstash.logback.stacktrace.ShortenedThrowableConverter">
<maxDepthPerThrowable>30</maxDepthPerThrowable>
<maxLength>2048</maxLength>
<shortenedClassNameLength>20</shortenedClassNameLength>
<exclude>sun\.reflect\..*\.invoke.*</exclude>
<exclude>net\.sf\.cglib\.proxy\.MethodProxy\.invoke</exclude>
<rootCauseFirst>true</rootCauseFirst>
<inlineHash>true</inlineHash>
</throwableConverter>
</encoder>
</appender>
<springProfile name="!local">
<root level="INFO">
<appender-ref ref="jsonConsoleAppender"/>
</root>
</springProfile>
</configuration>

How to select Logback appender based on property file or environment variable

I have configured logback xml for a spring boot project.
I want to configure another appender based on the property configured. We want to create an appender either for JSON logs or for text log, this will be decided either by property file or by environment variable.
So I am thinking about the best approach to do this.
Using filters to print logs to 1 of the file (either to JSON or to Txt). But this will create both of the appenders. I want to create only 1 appender.
Use "If else" blocks in logback XML file. To put if else around appenders, loggers seems untidy and error prone. So will try to avoid as much as possible.
So now exploring options where I can add appender at runtime.
So I want to know if it is possible to add appender at runtime. And will it be added before spring boots up or it could be done anytime in the project.
What could be the best approach to include this scenario.
As you're already using Spring, I suggest using Spring Profiles, lot cleaner than trying to do the same programmatically. This approach is also outlined in Spring Boot docs.
You can set an active profile from either property file:
spring.profiles.active=jsonlogs
or from environment value:
spring_profiles_active=jsonlogs
of from startup parameter:
-Dspring.profiles.active=jsonlogs
Then have separate configurations per profile:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="stdout-classic" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{dd-MM-yyyy HH:mm:ss.SSS} %magenta([%thread]) %highlight(%-5level) %logger{36}.%M - %msg%n</pattern>
</encoder>
</appender>
<appender name="stdout-json" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="ch.qos.logback.contrib.json.classic.JsonLayout">
<timestampFormat>yyyy-MM-dd'T'HH:mm:ss.SSSX</timestampFormat>
<timestampFormatTimezoneId>Etc/UTC</timestampFormatTimezoneId>
<jsonFormatter class="ch.qos.logback.contrib.jackson.JacksonJsonFormatter">
<prettyPrint>true</prettyPrint>
</jsonFormatter>
</layout>
</encoder>
</appender>
<!-- begin profile-specific stuff -->
<springProfile name="jsonlogs">
<root level="info">
<appender-ref ref="stdout-json" />
</root>
</springProfile>
<springProfile name="classiclogs">
<root level="info">
<appender-ref ref="stdout-classic" />
</root>
</springProfile>
</configuration>
As the previous answer states, you can set different appenders based on Spring Profiles.
However, if you do not want to rely on that feature, you can use environments variables as described in the Logback manual. I.e.:
<appender name="json" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="ch.qos.logback.contrib.json.classic.JsonLayout">
<jsonFormatter class="ch.qos.logback.contrib.jackson.JacksonJsonFormatter">
<prettyPrint>true</prettyPrint>
</jsonFormatter>
<appendLineSeparator>true</appendLineSeparator>
</layout>
</encoder>
</appender>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
%cyan(%d{HH:mm:ss.SSS}) %gray([%thread]) %highlight(%-5level) %magenta(%logger{36}) - %msg%n
</pattern>
</encoder>
</appender>
<root level="info">
<!--
! Use the content of the LOGBACK_APPENDER environment variable falling back
! to 'json' if it is not defined
-->
<appender-ref ref="${LOGBACK_APPENDER:-json}"/>
</root>

Make logback pattern part optional?

Is it possible to make parts of logbacks pattern layout depending on an attribute?
e.g. show bdid (...) just in the case when %X{bdid} exists?
This appender
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>bdid\(%X{bdid}\) - %d{HH:mm:ss.SSS} %msg%n</pattern>
</encoder>
</appender>
prints
bdid(0b5d3877-f3dd-4189-8b1b-489c8b617f2a) 18:22:25.206 if bdid exists, but prints
bdid() 18:22:20.928 if it doesn't.
How do I omit the empty bdid() in my log?
You can use the replace function, details are in the docs here. A working example is the following:
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%replace(bdid\(%X{bdid}\)){'bdid\(\)', ''} - %d{HH:mm:ss.SSS} %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration>
Test Function
public class PatternTest
{
#Test
public void test()
{
Logger logger = LoggerFactory.getLogger(PatternTest.class);
MDC.put("bdid", "hola");
logger.info("Check enclosed.");
MDC.remove("bdid");
logger.info("Check enclosed.");
}
}
Test output
bdid(hola) - 18:40:40.233 Check enclosed.
- 18:40:40.234 Check enclosed.

Strange behavior of Logback - empty files

I'm refurbishing old system that used logback, some simple stuff ( 3 appenders, 2 loggers ). Now in next version of system ( or re-implementation as the previous version was stolen with notebook and backup, only config file and binaries were already on robot ), I use the same config file, but all log files stays empty.
Strange thing is that it actually creates correct files and folders by the given patterns, so it definitely do something with the config file. Besides that, loggers and appenders aren't working at all.
I also tried to use various other configuration files I found on examples - not even one worked, so I'm suspicious that there is some collision between used libraries and logback. I tried to google it, but found nothing relevant or working.
Have anyone of you came around ( or hopefully through ) such a problem? Or please point at the wrong line...
Thx in advance...
Kamil
Next code shows initialization:
public static final String LOGGER_CONFIG_FILE = "hacs.logger.conf";
public static final String LOGGER_CONFIG_FILE_DEFAULT = "./conf/logconf.xml";
public static void main( String[] args ) {
File configurationFile = new File(HACSProperties.instance().getProperty(LOGGER_CONFIG_FILE, LOGGER_CONFIG_FILE_DEFAULT));
if( configurationFile.exists() ){
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.reset(); // When this is commented, logback works in some default configuration
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
configurator.doConfigure( LOGGER_CONFIG_FILE_DEFAULT );
System.out.println("Logger successfully configured..");
Logger log = LoggerFactory.getLogger("analytics");
log.info( "Please appear in file" );
} catch (JoranException je) {
System.out.println("Error - failed to configure logger. Please check configuration.");
je.printStackTrace();
System.exit( 1 );
}
} else {
System.out.println("Error - failed to configure logger - configuration file does not exist. Please check configuration.");
System.exit( 2 );
}
}
Config file itself:
<configuration>
<timestamp key="bySecond" datePattern="dd.MM.yyyy'_T'HH.mm.ss" timeReference="contextBirth" />
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>./logs/HACS_LAST_RUN.log</file>
<append>false</append>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n
</Pattern>
</layout>
</appender>
<appender name="FILE_PER_MINUTE" class="ch.qos.logback.core.FileAppender">
<file>./logs/PER_MINUTE/HACS-RUN-${bySecond}.log</file>
<append>false</append>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n
</Pattern>
</layout>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{HH:mm:ss.SSS} %level [%file:%line] %msg%n</Pattern>
</layout>
</appender>
<logger name="org.hibernate" additivity="false">
<level value="warn" />
<appender-ref ref="FILE" />
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE_PER_MINUTE" />
</logger>
<logger name="FILE_ONLY" additivity="false">
<level value="INFO" />
<appender-ref ref="FILE_PER_MINUTE" />
<appender-ref ref="FILE" />
</logger>
<root>
<level value="INFO" />
<appender-ref ref="FILE" />
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE_PER_MINUTE" />
</root>
</configuration>
List of libraries:
antlr-2.7.7.jar
aopalliance-1.0.jar
asm-3.3.jar
bcprov-jdk15-1.43.jar
cglib-2.2.jar
chronicle.jar
commons-collections-3.2.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
commons-pool-1.5.2.jar
cxf-2.3.0.jar
cxf-manifest.jar
cxf-xjc-boolean-2.3.0.jar
cxf-xjc-bug671-2.3.0.jar
cxf-xjc-dv-2.3.0.jar
cxf-xjc-ts-2.3.0.jar
dom4j-1.6.1.jar
FastInfoset-1.2.8.jar
felix.jar
geronimo-activation_1.1_spec-1.1.jar
geronimo-annotation_1.0_spec-1.1.1.jar
geronimo-javamail_1.4_spec-1.7.1.jar
geronimo-jaxws_2.2_spec-1.0.jar
geronimo-jms_1.1_spec-1.1.1.jar
geronimo-servlet_3.0_spec-1.0.jar
geronimo-stax-api_1.0_spec-1.0.1.jar
geronimo-ws-metadata_2.0_spec-1.1.3.jar
groovy-all-1.8.5.jar
h2-1.3.154.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate3.jar
javassist-3.12.0.GA.jar
jaxb-api-2.2.1.jar
jaxb-impl-2.2.1.1.jar
jaxb-xjc-2.2.1.1.jar
jettison-1.2.jar
jetty-continuation-7.1.6.v20100715.jar
jetty-http-7.1.6.v20100715.jar
jetty-io-7.1.6.v20100715.jar
jetty-server-7.1.6.v20100715.jar
jetty-util-7.1.6.v20100715.jar
jmdns.jar
jra-1.0-alpha-4.jar
js-1.7R1.jar
jsr311-api-1.1.1.jar
jta-1.1.jar
logback-access-1.0.1.jar
logback-classic-1.0.1.jar
logback-core-1.0.1.jar
neethi-2.0.4.jar
oro-2.0.8.jar
saaj-api-1.3.jar
saaj-impl-1.3.2.jar
serializer-2.7.1.jar
slf4j-api-1.6.4.jar
spring-aop-3.0.4.RELEASE.jar
spring-asm-3.0.4.RELEASE.jar
spring-beans-3.0.4.RELEASE.jar
spring-context-3.0.4.RELEASE.jar
spring-core-3.0.4.RELEASE.jar
spring-expression-3.0.4.RELEASE.jar
spring-jms-3.0.4.RELEASE.jar
spring-tx-3.0.4.RELEASE.jar
spring-web-3.0.4.RELEASE.jar
stax2-api-3.0.2.jar
velocity-1.6.4.jar
waiter-dns.jar
woodstox-core-asl-4.0.8.jar
wsdl4j-1.6.2.jar
wss4j-1.5.9.jar
xalan-2.7.1.jar
xml-resolver-1.2.jar
xmlbeans-2.4.0.jar
XmlSchema-1.4.7.jar
xmlsec-1.4.3.jar

Categories

Resources