log file is not generating using log4j2 in spring boot - spring-boot

I am using Log4j2 for logging with Spring Boot , but it is not creating the log file. Given below is my configuration for Log4j2 and dependencies i added. i tried all possible solution.
Log4j2 configuration -
Configuration:
name: Default
Properties:
Property:
name: log-path
value: "logs"
Appenders:
Console:
name: Console_Appender
target: SYSTEM_OUT
PatternLayout:
pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
File:
name: File_Appender
fileName: ${log-path}/logfile.log
PatternLayout:
pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
Loggers:
Root:
level: debug
AppenderRef:
- ref: Console_Appender
Logger:
- name: com.example
level: debug
AppenderRef:
- ref: File_Appender
level: error
dependencies used in build.gradle file:
configurations {
all*.exclude group:'org.springframework.boot', module: 'spring-boot-starter-logging'
all*.exclude module: 'logback-classic'
compileOnly {
extendsFrom annotationProcessor
}
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter'
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-starter-log4j2'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
}
Application file :
#SpringBootApplication
public class DemoApplication {
private static final Logger logger = LogManager.getLogger(DemoApplication.class);
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
logger.debug("This is a debug message");
logger.info("This is an info message");
logger.warn("This is a warn message");
logger.error("This is an error message");
logger.fatal("This is a fatal message");
}
}
After start appplication file getting logging in console but file is not generating.

Please Use below configuration file
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
<Properties>
<Property name="basePath">{base_path}</Property>
</Properties>
<Appenders>
<RollingFile name="fileLogger"
fileName="${basePath}/LogFileName.log"
filePattern="${basePath}/LogFileName_%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>%d{yyyy-MMM-dd HH:mm:ss.SSS} %5p [%50.50c] : %M - %m%n
</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
</Policies>
</RollingFile>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{yyyy-MMM-dd HH:mm:ss.SSS} %5p [%50.50c] : %M - %m%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="{your_package}" level="debug" additivity="true">
<appender-ref ref="fileLogger" level="debug" />
</Logger>
<Logger name="org.springframework" level="info"
additivity="true">
<appender-ref ref="fileLogger" level="info" />
</Logger>
<Root level="info" additivity="false">
<appender-ref ref="console" />
</Root>
</Loggers>
</Configuration>

your log filename fileName: ${log-path}/logfile.log has log-path refers a property, however that property is not defined
you need to add property in log4j file
<Properties>
<Property name="log-path">{log-path}</Property>
</Properties>

To support yaml format, need additional dependencies. After adding these dependencies, it is working fine.
compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml'
compile 'com.fasterxml.jackson.core:jackson-databind'

Related

Can't get file loggin to work with Log4j2 Slf4j in a Java 8 Spring app

I have a java spring 5 application that I deploy to Tomcat 8.5.15. I am now trying to upgrade the logging framework to Log4J2, I also use Slf4J. The problem right now is that I can't seem to log to a file (although it creates a file). It just logs to the console, why?. It's a multi module maven project. In the main "pom" i use these dependencies (for example):
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.13.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<scope>test</scope>
<version>1.7.30</version>
</dependency>
Here is the log4j2.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<Properties>
<Property name="basePath">logs</Property>
</Properties>
<Appenders>
<RollingFile name="fileLogger" fileName="logs/app-info.log" filePattern="logs/app-info-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
</RollingFile>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="foobar" level="debug" additivity="true">
<appender-ref ref="fileLogger" level="debug" />
</Logger>
<Root level="debug" additivity="false">
<appender-ref ref="console" />
</Root>
</Loggers>
</Configuration>
EDIT Here is the 2nd version of the config (This produces a file with a little content, but not from my code.. from testing stuff "DefaultTestContextBootstrapper"...) The log ends up here: mymodule/logs/app-info.log
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<Appenders>
<RollingFile name="fileLogger" fileName="logs/app-info.log" filePattern="logs/app-info-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
</RollingFile>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="info" additivity="false">
<appender-ref ref="fileLogger" />
</Root>
</Loggers>
</Configuration>
In the java code, I try to log like this:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
..
Logger logger = LoggerFactory.getLogger(MyClass.class);
logger.info("....");
Please edit fileName and filePattern. You wrote absolute path so the log file made at [System
root]/logs/
AS-IS
fileName="logs/app-info.log"
filePattern="logs/app-info-%d{yyyy-MM-dd}.log"
TO-BE
Case 1. Using relative path
If you write relative path then the log will saved at [project root directory]/LOG_FILE_DIR/LOG_FILE_NAME.log
fileName="./LOG_FILE_DIR/LOG_FILE_NAME.log"
filePattern="./LOG_FILE_DIR/LOG_FILE_NAME.log.gz"
Case 2. Using absolute path
If you write absolute path then the log will saved at C:/LOG_FILE_DIR/LOG_FILE_NAME.log
fileName="./LOG_FILE_DIR/LOG_FILE_NAME.log"
filePattern="C:/LOG_FILE_DIR/LOG_FILE_NAME.log.gz"
The problem was that my maven poms were not perfect. I declared the log4j2 in the root pom, but not in the modules, so the jars (log4j2...) were not in the classpath of the final war file, but log4j (1) was there, so I had to get rid of that dependency from a couple of poms. Then I used this config for it to work (log4j2.yml):
configuration:
name: Default
properties:
property:
- name: log-path
value: /logs
- name: archive
value: ${log-path}/archive
appenders:
Console:
PatternLayout:
pattern: '[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n'
name: Console-Appender
target: SYSTEM_OUT
File:
PatternLayout:
pattern: '[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n'
fileName: ${log-path}/amc.log
name: File-Appender
RollingFile:
DefaultRolloverStrategy:
max: '30'
PatternLayout:
pattern: '[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n'
Policies:
SizeBasedTriggeringPolicy:
size: 1 MB
fileName: ${log-path}/rollingfile.log
filePattern: ${archive}/rollingfile.log.%d{yyyy-MM-dd-hh-mm}.gz
name: RollingFile-Appender
loggers:
logger:
additivity: 'false'
appender-ref:
- level: info
ref: Console-Appender
- level: info
ref: File-Appender
- level: info
ref: RollingFile-Appender
level: debug
name: se.su.it.courseservice
root:
appender-ref:
ref: File-Appender
level: info

Sentry Log4j2 Kotlin Spring Boot Webflux - No issues published to Sentry

Having trouble getting sentry issues to publish.
Here's my setup.
I have exported my DSN as SENTRY_DSN.
src/main/kotlin/resources/log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="warn" packages="org.apache.logging.log4j.core,io.sentry.log4j2">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<Sentry name="Sentry" />
</appenders>
<loggers>
<root level="INFO">
<appender-ref ref="Console" />
<!-- Note that the Sentry logging threshold is overridden to the WARN level -->
<appender-ref ref="Sentry" level="WARN" />
</root>
</loggers>
</configuration>
build.gradle.kts
...
dependencies {
compile("io.sentry:sentry-log4j2:1.7.22")
...
}
Controller.kt
#RestController
#RequestMapping("/users")
class AuthenticationController(private val exampleService: ExampleService) {
private val logger = LogManager.getLogger(AuthenticationService::class)
#DeleteMapping("/session")
fun logout(): Mono<Response> {
logger.error("this is a error")
return exampleService.returnMono()
}
}
I expect this logger.error call to send a message to sentry.
Sentry SDK for Java recently got support for Webflux:
https://github.com/getsentry/sentry-java/pull/1529
That was on version 5.1.0-beta3 and GA is about to land in a few days/weeks:
https://github.com/getsentry/sentry-java/blob/main/CHANGELOG.md#510-beta3

Redirecting feign & ribbon logs to log4j2

I currently use spring cloud netflix with log4j2. The log4j2 configuration comes from the xml in the classpath. When I run the app, I see that the feign & ribbon logs are not being redirected to the logger specified in the configuration. I have configured log for com.netflix.ribbon & feign packages to be logged at debug level.
However, log configured for spring is properly redirecting to the specified appender, ribbon & feign are not.
I am using gradle with spring-boot-starter-logging ignored & added spring-boot-starter-log4j2 in as part of my build.
I see that feign has a way by which we can configure slf4j, but since we use annotation driven feign support, I cant configure the feign to use slf4j for logging.
Any help is appreciated.
My log4j2.xml looks some what like
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="log-path">logs</Property>
<Property name="log-fileName">test</Property>
</Properties>
<Appenders>
<Console name="console-log" target="SYSTEM_OUT">
<PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
</Console>
<RollingFile name="trace-log" fileName="${log-path}/${log-fileName}-trace.log" filePattern="${log-path}/${log-fileName}_trace-%d{yyyy-MM-dd}.log">
<PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
</RollingFile>
<RollingFile name="error-log" fileName="${log-path}/${log-fileName}-error.log" filePattern="${log-path}/${log-fileName}_error-%d{yyyy-MM-dd}.log">
<PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<logger name="org.springframework" level="trace" additivity="false">
<AppenderRef ref="trace-log" />
</logger>
<logger name="feign" level="trace" additivity="false">
<AppenderRef ref="trace-log" />
</logger>
<logger name="com.netflix.ribbon" level="trace" additivity="false">
<AppenderRef ref="trace-log" />
</logger>
<Root level="info">
<AppenderRef ref="console-log"></AppenderRef>
<AppenderRef ref="error-log" level="ERROR"/>
</Root>
</Loggers>
</Configuration>
PS: The reason for debugging feign/ribbon is to understand a weird feign behavior between two different machines in our micro services setup
Looking at Spring Cloud's FeignClientFactoryBean shows that you can optionally autowire a bean of type feign.Logger.Level. Try registering such a bean in your #Configurationusing
#Bean
public feign.Logger.Level feignLoggerLevel() {
return feign.Logger.Level.FULL;
}
#jensfischerhh's answer would fix many cases but looks mistakenly missed one thig.
You need to config feign generated class's logger level with feignLoggerLevel Bean.
Both config must be exist together.
related doccument in spring-cloud-netflix
bean config ( in #Configuration annotated class )
#Bean
public feign.Logger.Level feignLoggerLevel() {
return feign.Logger.Level.FULL;
}
log config
</Configuration>
<Loggers>
<logger name="your.feign-interface-package" level="trace">
</Loggers>
</Configuration>

Spring Boot logging pattern

I have a problem with configuration on Logback in a Spring Boot application. I want my consoleAppender to look like the default Spring Boot console appender. How to inherit pattern from Spring Boot default console appender?
Below is my consoleAppender configuration
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern class="org.">
%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
</Pattern>
</layout>
</appender>
Once you have included the default configuration, you can use its values in your own logback-spring.xml configuration:
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true">
<!-- use Spring default values -->
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
…
</configuration>
You can find Spring Boot logback console logging pattern in defaults.xml file:
spring-boot-1.5.0.RELEASE.jar/org/springframework/boot/logging/logback/defaults.xml
Console pattern:
<property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx
</Pattern>
</layout>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
</root>
</configuration>
If you are using application.yml for your config, you can set the logging pattern this way:
logging:
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} | %-5level | %logger{1.} | %msg%n"
level:
org.springframework: WARN
com.ulisesbocchio.jasyptspringboot: WARN
com.example.test: DEBUG
You can override the logging level on the command line. For example:
$ java -Dlogging.level.com.example.test=TRACE -jar my-example.jar
It's been some time since this question was asked but since I had the problem myself recently and couldn't find an answer I started digging a bit deeper and found a solution that worked for me.
I ended up using the debugger and take a look at the default appenders attached to the logger.
I found this pattern to be working as desired for me:
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %5p 18737 --- [%t] %-40.40logger{39} : %m%n%wEx</pattern>
EDIT: The pattern is not entirely correct, I saw that runtime some values had already been instantiated (in this case 18737 ---) i will look into the proper variable to substitute there. It does contain the format for fixed length columns though
EDIT 2: Ok, I took another look at the debugger contents. This you can also do yourself by looking at the contents of a logger instance:
Debugger(eclipse) Logger Contents
So I ended up using the pattern used in the consoleAppender:
%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(18971){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx
As can be seen here:
Debugger: detailed contents of the encoder pattern
Logging pattern can be configured using application.properties file
Example :
# Logging pattern for the console
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
You can use below pattern :
%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${sys:PID} --- [%15.15t] %-40.40logger{1.} : %m%n%wEx
Note that you can also customize the imported properties.
But beware that at least with spring boot 1.4.3 if you want to customize the properties imported from the defaults.xml, then the customization should be placed BEFORE the include.
For example this customizes the priority to 100 character wide:
<configuration scan="true">
<property name="LOG_LEVEL_PATTERN" value="%100p" />
<!-- use Spring default values -->
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
</layout>
</appender>
<logger name="hu" level="debug" additivity="false">
<appender-ref ref="CONSOLE" />
</logger>
<root level="warn">
<appender-ref ref="CONSOLE" />
</root>
</configuration>
But this is NOT:
<configuration scan="true">
<!-- use Spring default values -->
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property name="LOG_LEVEL_PATTERN" value="%100p" />
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
</layout>
</appender>
<logger name="hu" level="debug" additivity="false">
<appender-ref ref="CONSOLE" />
</logger>
<root level="warn">
<appender-ref ref="CONSOLE" />
</root>
</configuration>
For those who'd like to use Łukasz Frankowski's answer (which looks like the cleanest solution here), but in a groovy version, the "problematic" {$PID:- } part can be expanded like in the following:
logback-spring.groovy
import ch.qos.logback.classic.PatternLayout
import ch.qos.logback.core.ConsoleAppender
import org.springframework.boot.logging.logback.ColorConverter
import org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter
import org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter
import static ch.qos.logback.classic.Level.INFO
conversionRule("clr", ColorConverter)
conversionRule("wex", WhitespaceThrowableProxyConverter)
conversionRule("wEx", ExtendedWhitespaceThrowableProxyConverter)
appender("STDOUT", ConsoleAppender) {
layout(PatternLayout) {
def PID = System.getProperty("PID") ?: ''
pattern = "%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx"
}
}
root(INFO, ["STDOUT"])
This worked for me, adding following line to resources/log4j2.properties file
appender.console.layout.pattern = %d{ISO8601} - info: %msg%n ( your custom pattern goes here )
The spring documentation has an example of the logback.xml that defines the default.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
<logger name="org.springframework.web" level="DEBUG"/>
</configuration>

No extra logging in the console with log4j

I'm new at this logging stuff and i want see logging from spring to see all the beans created.
So I want to try logging with log4j but no extra loggin appear in the console.
I follow some example to make my logging.
Here's my configuration :
pom.xml
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-rc2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-rc2</version>
</dependency>
log4j.properies
# Root logger option
log4j.rootLogger=INFO, stdout
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
log4j.logger.org.springframework=INFO,stdout
My Controller Class
//Import log4j classes.
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
#Transactional
#Controller
public class Inscription {
...
static final Logger logger = LogManager.getLogger(Inscription.class);
...
#RequestMapping(value="/")
public String Test(ModelMap model) {
...
//log it via log4j
logger.debug(model);
...
}
}
is the log4j.property loaded ? (i put it twice to make sure)
what mean this logger.debug(model); is it requierd to make logging or just log4j.property is enough ?
I have created a log4j2.xml in classpath (src folder) it will detect automatically by log4j
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="CONSOLE" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="ALL">
<AppenderRef ref="CONSOLE"/>
</Root>
<Logger name="controller" level="ALL" >
<AppenderRef ref="CONSOLE"/>
</Logger>
</Loggers>
</Configuration>

Resources