Print Class Name, Method name and line number using Logger's info() - java

I already configured logback file to get classname, method name and line number.
<pattern> %d{HH:mm:ss.SSS} [%thread] %-5level %class{36}.%M %L - %msg%n </pattern>
I want to print log message when entering and existing method. How can i do that within the class using info() method. I used the code below. But it didnt print what i wanted.
I use org.slf4j.Logger and Logback logging
LOG.info("Entering " + );
This is what I got :
14:41:48.097 [main] INFO c.a.j.orgchart.CsvPersonReader - Entering
I want to print something like this:
14:41:48.097 [main] INFO c.a.j.orgchart.CsvPersonReader.[MethodName] [Linenumber] - Entering

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %class{36}.%M %L - %msg%n</pattern>
</encoder>
</appender>

logging.pattern.console=%14date{dd.MM.yyyy kk:mm:ss.SSS} [%1level] %30.30logger{1}\.%replace(%replace(%replace(%caller{3..4}){'[\n\r]',''}){'\\(.+\\)$','()'}){'^.+\\.',''} : %msg%n
Above pattern outputs result like below:
10.05.2019 08:35:05.337 [INFO] epositoryConfigurationDelegate.forEach() : Bootstrapping Spring Data repositories in DEFAULT mode.
...
Here's another option if you want to printout little a bit polished version of it.
logging.pattern.console=%14date{dd.MM.yyyy kk:mm:ss.SSS} [%1level] %40.40logger{0}\.%-35.35replace(%replace(%replace(%caller{3..4}){'[\n\r]',''}){'\\(.+\\)$','()'}){'^.+\\.',''} : %msg%n
Output looks like this:
10.05.2019 08:45:57.228 [DEBUG] RepositoryConfigurationDelegate.forEach() : Bootstrapping Spring Data repositories in DEFAULT mode.
10.05.2019 08:45:59.651 [INFO] RepositoryConfigurationDelegate.forEach() : Finished Spring Data repository scanning in 384ms. Found 3 repository interfaces.
10.05.2019 08:46:00.524 [INFO] trationDelegate$BeanPostProcessorChecker.doCreateBean() : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$3f00c757] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
10.05.2019 08:46:03.828 [INFO] TomcatWebServer.getWebServer() : Tomcat initialized with port(s): 8080 (http)
10.05.2019 08:46:03.896 [INFO] StandardService.start() : Starting service [Tomcat]
10.05.2019 08:46:03.897 [INFO] StandardEngine.start() : Starting Servlet engine: [Apache Tomcat/9.0.14]
1
Just keep in mind that "...Generating the caller class information is
not particularly fast. ..."
logback patternlayout docs

Related

Having space in front of logged messages in logback

My Logback pattern in logback.xml file as follows
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} %yellow([%X{Auth-Scopes:-},%X{Auth-Principal:-},%X{Auth-Organization:-}]) %magenta(${PID:-}) --- [%15.15t] %cyan(%-40.40logger{39}) : %m %n ${LOG_EXCEPTION_CONVERSION_WORD:-%xEx}</pattern>
My problem is there is space in front of log lines from above pattern as follows
2021-08-18 03:40:00.017 DEBUG [test-service,,,] [,,] 1 --- [test-7] a.b.c.Test : Test
I am still trying to figure out what this cause for some time. Any help would be really appreciated .
Last parameter causes the problem.
You can try this one;
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} %yellow([%X{Auth-Scopes:-},%X{Auth-Principal:-},%X{Auth-Organization:-}]) %magenta(${PID:-}) --- [%15.15t] %cyan(%-40.40logger{39}) : %m ${LOG_EXCEPTION_CONVERSION_WORD:-%xEx} %n</Pattern>

Log4J throws illegal char <:> exception while processing Appender File in Springboot WebApp

I am using Log4J along with Springboot in my J2EE based WebApp.
It throws illegal char <:> exception while processing Appender File.
Log4J version: 2.11.1
The logger properties in my application.properties file are as below
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
logging.file=log\\web.log
I understand that it's because of the character colon ':' , but even after trying out different patterns, I still get the same error message.
I don't know where the ${sys:LOG_PATH} part is coming from and how to fix this.
Can someone please help.
Attaching the error stack trace as well.
Thanks in advance :)

the latest spring-rabbit don't support encoder tag?

I have a question about this, i am going send the logback logs to rabbit, and i use spring-rabbit, as i need to send the data with json format, so i used LoggingEventCompositeJsonEncoder, here are my configuration
<appender name="AMQP" class="org.springframework.amqp.rabbit.logback.AmqpAppender">
<!--<layout>-->
<!--<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>-->
<!--</layout>-->
<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<pattern>
<pattern>
{ "level": "%level" }
</pattern>
</pattern>
</encoder>
<host>127.0.0.1</host>
<port>5672</port>
<username>guest</username>
<password>guest</password>
<routingKeyPattern>testroute</routingKeyPattern>
<exchangeName>logs</exchangeName>
<declareExchange>true</declareExchange>
<generateId>true</generateId>
<charset>UTF-8</charset>
<durable>true</durable>
<deliveryMode>PERSISTENT</deliveryMode>
</appender>
but when i start the application, i got the error as below :
java.lang.IllegalStateException: Logback configuration error detected: ERROR in ch.qos.logback.core.joran.spi.Interpreter#16:88 - no applicable action for [encoder], current ElementPath is [[configuration][appender][encoder]]
ERROR in ch.qos.logback.core.joran.spi.Interpreter#18:22 - no applicable action for [pattern], current ElementPath is [[configuration][appender][encoder][pattern]]
ERROR in ch.qos.logback.core.joran.spi.Interpreter#19:26 - no applicable action for [pattern], current ElementPath is [[configuration][appender][encoder][pattern][pattern]]
at org.springframework.boot.logging.logback.LogbackLoggingSystem.loadConfiguration(LogbackLoggingSystem.java:162)
at org.springframework.boot.logging.AbstractLoggingSystem.initializeWithConventions(AbstractLoggingSystem.java:81)
at org.springframework.boot.logging.AbstractLoggingSystem.initialize(AbstractLoggingSystem.java:59)
at org.springframework.boot.logging.logback.LogbackLoggingSystem.initialize(LogbackLoggingSystem.java:115)
at org.springframework.boot.logging.LoggingApplicationListener.initializeSystem(LoggingApplicationListener.java:303)
at org.springframework.boot.logging.LoggingApplicationListener.initialize(LoggingApplicationListener.java:276)
at org.springframework.boot.logging.LoggingApplicationListener.onApplicationEnvironmentPreparedEvent(LoggingApplicationListener.java:239)
at org.springframework.boot.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:212)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:74)
at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:325)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:296)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
That's correct the org.springframework.amqp.rabbit.logback.AmqpAppender is a AppenderBase extension, not an OutputStreamAppender which supports that encoder option.
However I'm pretty sure we can add support for it and instead of raw msgBody.getBytes() call already this.encoder.encode(event).
The JIRA on the matter: https://jira.spring.io/browse/AMQP-760.

My EvaluatorFilter doesn't work in Spring Boot + logback-access.xml

I've managed to integrate logback-access.xml with a Spring Boot on Tomcat project but for the life of me I cannot get it to respect my ch.qos.logback.core.filter.EvaluatorFilter. It definitely sees and uses my logback-access.xml file (if I change the encoder.pattern the output messages change), but seems oblivious of the filter I configure there; I don't get the effect I am looking for which is suppression of any access log messages from the /healthz URL and I don't see my System.out.println cry for help
The logback-access.xml file looks like
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator>
<expression>
System.out.println("ROBERT!!!! " + formattedMessage);
return formattedMessage.contains("/healthz");
</expression>
</evaluator>
<OnMismatch>NEUTRAL</OnMismatch>
<OnMatch>DENY</OnMatch>
</filter>
<encoder>
<pattern>%h %l %u %user %date "%r" %s %b</pattern>
</encoder>
</appender>
<appender-ref ref="CONSOLE"/>
</configuration>
The build.gradle has the requisite dependencies
compile(group: 'net.rakugakibox.springbootext', name: 'spring-boot-ext-logback-access', version: '1.6')
compile group: 'org.codehaus.janino', name: 'janino', version: '3.0.7'
The logging output mocks me...
0:0:0:0:0:0:0:1 - - - 22/Jun/2017:15:16:17 -0700 "GET /healthz HTTP/1.1" 200 27
0:0:0:0:0:0:0:1 - - - 22/Jun/2017:15:18:18 -0700 "GET /v1/scouting_activities/fcdc7aae-4f11-4476-bb81-6d5e3f52e1b4 HTTP/1.1" 200 1939
How do I get an ch.qos.logback.core.filter.EvaluatorFilter in logback-access.xml under Spring Boot 1.4.1 to work and skip the GET /healthz requests?
If you debug the logback configuration you will see the problem(<configuration debug="true">).
11:03:53,559 |-ERROR in ch.qos.logback.access.boolex.JaninoEventEvaluator#649725e3 - Could not start evaluator with expression [System.out.println("ROBERT!!!! " + formattedMessage);
return false;] org.codehaus.commons.compiler.CompileException: Line 1, Column 52: Expression "formattedMessage" is not an rvalue
at org.codehaus.commons.compiler.CompileException: Line 1, Column 52: Expression "formattedMessage" is not an rvalue
The problem is that logback-access does not operate on ILoggingEvent, rather it operates on IAccessEvent.
There are JaninoEventEvaluator classes for each type of event.
The logback-access evaluator does not have the formattedMessage value.
It does however have the event value which is an instance of a IAccessEvent.
So just change your expression to the below and it should work.
<expression>
System.out.println("ROBERT!!!! " + event.getRequestURI());
return event.getRequestURI().contains("/healthz");
</expression>

Why doesn't Slf4j/Logback log filename and row number

I'm having problems with my logging where slf4j doesn't log the filename and row number of the message/stacktrace.
Code:
private static Logger log = LoggerFactory.getLogger(SomeService.class);
#Override
public void aService(ServiceAdmin sa) throws Exception {
log.debug(LoggerFactory.class.toString());
log.debug(log.getClass().getName());
log.debug("Setup Example");
SomeService.setDefault(Example.getInstance());
log.debug("Example finished");
}
Log:
2015-04-20 14:47:26.573 DEBUG [main] null:-1 - class org.slf4j.LoggerFactory
2015-04-20 14:47:26.574 DEBUG [main] null:-1 - ch.qos.logback.classic.Logger
2015-04-20 14:47:26.574 DEBUG [main] null:-1 - Setup Example
2015-04-20 14:47:26.575 DEBUG [main] null:-1 - SomeService finished
This is pars of my logback.xml that relates to this class
<logger name="com.bredband.nexusgw.services">
<level value="debug" />
<appender-ref ref="nexusservice" />
</logger>
<appender name="nexusservice"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>/var/log/nexus/nexusjgw/jgw/Service.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<FileNamePattern>/var/log/nexus/nexusjgw/jgw/Service.log.%i
</FileNamePattern>
<MinIndex>1</MinIndex>
<MaxIndex>5</MaxIndex>
</rollingPolicy>
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>200MB</MaxFileSize>
</triggeringPolicy>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %5p [%t] %F:%L - %m%n</Pattern>
</layout>
</appender>
Has anyone seen this before and can point me in the right direction?
BR
Stefan
-- Update --
I changed the %F to %C, but that didn't change anything in the logs. Then I tried to set debug = "on" in the javac header in my ant file and now it's logging classname and line number.
2015-04-21 08:28:55.910 DEBUG [main] Service.java:20 - class org.slf4j.LoggerFactory
2015-04-21 08:28:55.911 DEBUG [main] Service.java:21 - ch.qos.logback.classic.Logger
2015-04-21 08:28:55.911 DEBUG [main] Service.java:22 - Setup Example
2015-04-21 08:28:55.912 DEBUG [main] Service.java:24 - Example finished
Although this is working, it's not something I've changed before. The only thing that has changed in this project over time is the addition of other external jars. I'm not really sure how adding a duplicate/newer/older version of slf4j in another external jar would affect the logging though, any version should look for the logback file?
-- Update --
After checking alot of historical checkins of the build.xml file I found that we actually had debug = "on" earlier and the problem may actually have been introduced by this parameter beeing set to "off".
Thank you for your help.
BR
Stefan
You should first make sure that you compile your application with debug information. If calling javac directly, then it is the -g command-line parameter. However most build tools (like maven or ant) have a specific way to provide this parameter.
You may also want to replace %F with %C, which should work without the debug information.

Categories