Reputation: 125
I want to save the infos of the logins that have succeded into a log file, I thought of creating a new level of logging and save into the log file only the logs with that specific level. This is how I tried but I can't have it work properly:
log4j2-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%style{%d{ISO8601}}{white} %highlight{%-5level }[%style{%t}{bright,blue}] %style{%C{1.}}{bright,yellow}: %msg%n%throwable" />
</Console>
<RollingFile name="RollingFile"
fileName="./logs/historicLog.log"
filePattern="./logs/$${date:yyyy-MM}/spring-boot-logger-log4j2-%d{-dd-MMMM-yyyy}-%i.log.gz">
<PatternLayout>
<pattern>%d %p %C{1.} [%t] %m%n</pattern>
</PatternLayout>
<Policies>
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy
size="10 MB" />
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console" />
<AppenderRef ref="RollingFile" />
</Root>
<Logger name="login" level="info">
<AppenderRef ref="RollingFile" />
</Logger>
</Loggers>
</Configuration>
build.gradle dependencies:
dependencies {
implementation 'org.springframework.cloud:spring-cloud-config-server:3.0.5'
implementation 'org.springframework.boot:spring-boot-starter-web:2.6.1'
implementation 'org.springframework.boot:spring-boot-starter-log4j2'
implementation 'org.springframework.boot:spring-boot-starter-actuator:2.6.1'
testImplementation 'org.springframework.boot:spring-boot-starter-test:2.6.1'
}
configurations.implementation {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
AuthenticationService.java
private static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(AuthenticationServiceApplication.class);
....
logger.log(Level.forName("login", 850), user.getUsername() + " logged in as admin");
Thank you in advance.
Upvotes: 0
Views: 1130
Reputation: 44535
Your root logger is still set on INFO
, and your com.authenticationservice
logger is on TRACE
, both have level IDs lower then 850, so any log statements with a higher level will not be written.
However, i would suggest to not use a custom log level, but rather a specific logger name and configure that one then. E.g. like this:
In your AuthenticationService.java:
private static final org.apache.logging.log4j.Logger logger = LogManager.getLogger("login");
In your log4j2-spring.xml:
<Logger name="login" level="info"> // Note, that you should have the same level configured than what you use in the code to log the messages
<AppenderRef ref="RollingFile" />
</Logger>
This would write all login related logs in the log file configured at RollingFile
. With that solution you are a lot more flexible than with using a custom level, since you can redirect this to separate files, combine the statements with other loggers etc.
Upvotes: 1