log4j2 Logger Only Works in Primary Class - Spring Boot - java

I'm trying to use log4j2's rolling logs functionality for a new app, but I can't get the logger to work outside the main class, trying various combos of static, final, and autowired configs in the secondary classes.
All classes and config below. What am I missing or incorrectly calling?
POM.XML
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
Root Class:
#SpringBootApplication
public class DocumentServiceApplication {
private static final Logger logger = LogManager.getLogger(DocumentServiceApplication.class);
public static void main(String[] args) {
//these work.
logger.debug("Logger correctly configured debug.");
logger.error("Logger correctly configured error.");
logger.info("Logger correctly configured info.");
SpringApplication.run(DocumentServiceApplication.class, args);
}
}
Secondary (Web API) Class:
#RestController
public class DocumentController {
#Autowired
private PPAFileService ppaFileService;
private static final Logger logger = LogManager.getLogger(DocumentController.class);
#GetMapping("/ppa/process")
#ResponseBody
public ResponseEntity<String> process( ) throws Exception
{
try {
//this logging gives no error and no entry on console or file.
logger.debug("Received request for PPA file.");
...
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
}
Log Output
2019-04-10 15:37:56 DEBUG Logger correctly configured debug.
2019-04-10 15:37:56 ERROR Logger correctly configured error.
2019-04-10 15:37:56 INFO Logger correctly configured info.
log4j2.properties
status = error
name = PropertiesConfig
#Make sure to change log file path as per your need
property.filename = D:\\projects\\app\\application.log
filters = threshold
filter.threshold.type = ThresholdFilter
filter.threshold.level = debug
appenders = rolling
appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${filename}
appender.rolling.filePattern = application-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=10MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 20
loggers = rolling
logger.rolling.name = com.app.documentservice
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = RollingFile

Related

Simplification of log4j2.properties file

I am testing for migration from log4j 1 to log4j 2.
The following example works correctly.
But I would like to know if the log4j2.properties can be simplified, as I find it somewhat "verbose".
The idea is that all use of the XXX logger is recorded to the XXX.log file.
Likewise, all use of the YYY logger is recorded in the YYY.log file.
And everything else "undefined" is written over Default.log
As I say, it already works as I intend, but I would like to know if the log4j2.properties can be minimized in some way, since my real application uses about 9 loggers.
package test;
import org.apache.log4j.Logger;
public class TestLog4j2 {
public static void main(String[] args) {
System.out.println("START");
Logger log = null;
log = Logger.getLogger("XXX");
log.debug("Running method 'main' of class 'TestLog4j2' (want to be logged to XXX.log file)");
log = Logger.getLogger("YYY");
log.debug("Running method 'main' of class 'TestLog4j2' (want to be logged to YYY.log file)");
log = Logger.getLogger(TestLog4j2.class);
log.debug("Running method 'main' of class 'TestLog4j2' (want to be logged to Default.log file)");
System.out.println("END");
}
}
#Definicion de propiedades reutilizables
property.APP_LOG_ROOT = C:/logs
property.PATRON_LOG_DETALLADO = %-5p: [%d{yyyyMMddHHmmss.SSS}] [%c{1}]: [%C{1}.%M.%L]: %m%n
#Definicion appender de traza a fichero Default para logs sin logger definido
appender.Default.type = RollingFile
appender.Default.name = Default
appender.Default.fileName = ${APP_LOG_ROOT}/Default.log
appender.Default.filePattern = ${APP_LOG_ROOT}/Default.log.%d{yyyy-MM-dd}
appender.Default.layout.type = PatternLayout
appender.Default.layout.pattern = ${PATRON_LOG_DETALLADO}
appender.Default.policies.type = Policies
appender.Default.policies.time.type = TimeBasedTriggeringPolicy
appender.Default.policies.time.interval = 1
#Definicion appender de traza XXX
appender.XXX.type = RollingFile
appender.XXX.name = XXX
appender.XXX.fileName = ${APP_LOG_ROOT}/XXX.log
appender.XXX.filePattern = ${APP_LOG_ROOT}/XXX.log.%d{yyyy-MM-dd}
appender.XXX.layout.type = PatternLayout
appender.XXX.layout.pattern = ${PATRON_LOG_DETALLADO}
appender.XXX.policies.type = Policies
appender.XXX.policies.time.type = TimeBasedTriggeringPolicy
appender.XXX.policies.time.interval = 1
#Definicion appender de traza YYY
appender.YYY.type = RollingFile
appender.YYY.name = YYY
appender.YYY.fileName = ${APP_LOG_ROOT}/YYY.log
appender.YYY.filePattern = ${APP_LOG_ROOT}/YYY.log.%d{yyyy-MM-dd}
appender.YYY.layout.type = PatternLayout
appender.YYY.layout.pattern = ${PATRON_LOG_DETALLADO}
appender.YYY.policies.type = Policies
appender.YYY.policies.time.type = TimeBasedTriggeringPolicy
appender.YYY.policies.time.interval = 1
#Definicion logger de traza XXX
logger.XXX.appenderRef.XXX.ref = XXX
logger.XXX.name = XXX
logger.XXX.level = DEBUG
logger.XXX.additivity = false
#Definicion logger de traza YYY
logger.YYY.appenderRef.YYY.ref = YYY
logger.YYY.name = YYY
logger.YYY.level = DEBUG
logger.YYY.additivity = false
#Definicion rootlogger
rootLogger.level = DEBUG
rootLogger.appenderRef.Default.ref = Default

Getting Log4j2 errors

My log4j2 properties file:
status = warn
name= properties_configuration
#Directory path where log files will be stored
property.basePath = ./log/
#File logger
appender.rolling.type = RollingFile
appender.rolling.name = fileLogger
appender.rolling.fileName= ${basePath}app.log
appender.rolling.filePattern= ${basePath}app_%d{yyyyMMdd}.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %msg%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.delete.type = Delete
appender.rolling.strategy.delete.basePath = ${basePath}
appender.rolling.strategy.delete.maxDepth = 1
appender.rolling.strategy.delete.ifLastModified.type = IfLastModified
appender.rolling.strategy.delete.ifLastModified.age = 30d
#Root logger configuration
rootLogger.level = info
rootLogger.additivity = false
rootLogger.appenderRef.rolling.ref = fileLogger
I'm using Lombok #Log4j2 annotation:
#Log4j2
public class BotApplication {
public static void main(String[] args) {
ApiContextInitializer.init();
TelegramBotsApi telegram = new TelegramBotsApi();
Bot bot = new Bot();
try {
telegram.registerBot(bot);
log.info("Bot successfully connected.");
} catch (TelegramApiRequestException e) {
log.error("Can't start Bot. Error: {}", e.getMessage());
}
}
}
Application writes logs to file correctly, but always when i run my app i got errors in my console:
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Seems that these errors don't affect to the logger, but I would like to remove them somehow.
Error messages that being with "log4j:WARN" are coming from log4j 1.x. This error means you have the log4j 1.x jar in your classpath but do not have a Log4j 1.x configuration present.
If you do not want to use log4j 1 (and you shouldn't) then add the log4j-1.2-api jar from Log4j 2 to your project.

log4j2 doesn't save to log file

I have configuration for log4j2 in properties file. Logger sends output to the console but not to the file. It creates log file but it doesn't update it with content. What can be missing in my configuration file?
log4j2.properties
status = error
name = PropertiesConfig
property.filename = /usr/local/logs/kit.log
filters = threshold
filter.threshold.type = ThresholdFilter
filter.threshold.level = debug
appenders = rolling
appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${filename}
appender.rolling.filePattern = debug-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=10MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 20
loggers = rolling
logger.rolling.name = org.kit
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = RollingFile
Test class
package org.kit.log;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LogTest {
private static final Logger logger = LogManager.getLogger(LogTest.class);
public static void main(String[] args) {
logger.debug("Hello world - debug log");
logger.info("Hello world - info log");
logger.warn("Hello world - warn log");
logger.error("Hello world - error log");
}
}
You can try setting the first line in the configuration to status = TRACE to show Log4j2 internal logging on the console. This may help determine any problems with the configuration.
Also, can you try configuring a rootLogger instead of a named logger?
rootLogger.level = info
rootLogger.appenderRef.rolling.ref = RollingFile

log4j fails to write into file

I'm using Spring + Log4j. I can see my logs in Eclipse console, but Log4j failed to write into target file.
My web.xml:
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
My log4j.properties: the target file is D:/home/site/wwwroot/logs/swinguserver.log
### set log levels ###
log4j.rootLogger = DEBUG, CONSOLE, LOGFILE
### Settings for Console ###
log4j.appender.CONSOLE = org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold = INFO
log4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### Settings for File ###
log4j.appender.LOGFILE = org.apache.log4j.DailyRollingFileAppender
log4j.appender.LOGFILE.File = D:\/home\/site\/wwwroot\/logs\/swinguserver.log
log4j.appender.LOGFILE.Append = true
log4j.appender.LOGFILE.Threshold = DEBUG
log4j.appender.LOGFILE.layout = org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.LOGFILE.DatePattern = '_'yyyyMMdd'.log'
The java code I use to test Spring + Log4j, the log level is INFO and the log content is : JSONController.getShopInJSON(), name = xxxxxx
#Controller
#RequestMapping("/test")
public class JSONController {
private static final Logger logger = Logger
.getLogger(JSONController.class);
#RequestMapping(value="{name}", method = RequestMethod.GET)
public #ResponseBody Shop getShopInJSON(#PathVariable String name) {
logger.info("JSONController.getShopInJSON(), name = " + name);
Shop shop = new Shop();
shop.setName(name);
shop.setStaffName(new String[]{"mkyong1", "mkyong2"});
return shop;
}
}
When I visit the test url in browser, I can see the desired log in Eclipse console:
However, when I check D:/home/site/wwwroot/logs/swinguserver.log, there is nothing about the test log:
Any suggestion? Thank you guys.
It turns out I imported the wrong Logger package... Nothing is wrong with the code I posted.
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File= D:/home/site/wwwroot/logs/swinguserver.log
Try above two lines insted of below two lines in your program
log4j.appender.LOGFILE = org.apache.log4j.DailyRollingFileAppender
log4j.appender.LOGFILE.File = D:/home/site/wwwroot/logs/swinguserver.log

Log4j 2: How to add references from my classes in my log4j.properties [duplicate]

This question already has answers here:
Log4j Log at all Classes Level
(2 answers)
Closed 6 years ago.
is my first question, sorry If I make a mistake asking my question.
Well this is my doubt about log4j2.(I use spring framework java)
My goal is write in a FILE all logs generated in classes wich have a Logger instance.
For this purpose I have the following log4j.properties file:
name=PropertiesConfig
property.filename = C:/sts-bundle/Tomcat 7.0/logs
appenders = console,rolling
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{dd MMM yyyy HH:mm:ss,SSS} [%t] %c{5} - %msg%n
appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${filename}/fnelLog-${date:dd-MM-yyyy}.log
appender.rolling.filePattern = ${filename}/fnelLog-%d{dd-MM-yyyy}-%i.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = [%-5level] %d{dd MMM yyyy HH:mm:ss,SSS} [%t] %c{5} - %msg%n
appender.rolling.policies.type = Policies
#appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
#appender.rolling.policies.time.interval = 2
#appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=50MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 4
loggers = rolling
############ HERE IS MY PROBLEM, I Only reference to this class, but I want to add another,
############ so I can write all logs in a file described in lines before
logger.rolling.name = fnel.bcp.org.main.TestMain
logger.rolling.level = debug
#logger.rolling.additivity = false
logger.rolling.appenderRefs = rolling
logger.rolling.appenderRef.rolling.ref = RollingFile
rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
And Now here are the two clases which I used the Logger interface.
public class FooClass {
private static Logger logger = LogManager.getLogger(FooClass.class);
public void testLog4j() {
// TODO Auto-generated method stub
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");
}
}
public class TestMain {
private static Logger logger = LogManager.getLogger(TestMain.class);
public static void main(String[] args) {
FooClass foo = new FooClass();
//Calling foo method
foo.testLog4j();
// TODO Auto-generated method stub
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");
}
}
And these are the output in console
So, my question is how can I add FooClass in my log4j.properties file. Because I added next to TestMain class like this " fnel.bcp.org.main.TestMain , fnel.bcp.org.main.FooClass" , but not work.
I tried to separate in different logger.rolling.name, but didn't work too.
Change the line
logger.rolling.name = fnel.bcp.org.main.TestMain
to
logger.rolling.name = fnel.bcp.org.main
this will cause any class in the fnel.bcp.org.main package to be directed to the RollingFile appender. Alternatively, if you want everything in the file you can just remove your logger definition and change the root logger to be directed to RollingFile instead of STDOUT.

Categories

Resources