log4j 2 - configuration issue - java

I am trying to configure log4j 2.0 to report logs.
My config is saved as log4j2.xml and this is its content:
<?xml version="1.0" encoding="UTF-8"?>
<configuration name="PRODUCTION" status="OFF">
<appenders>
<RollingFile name="MyFileAppender"
fileName="../Logs/app.log"
filePattern="../Logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout>
<pattern>%d %p %C{1.} [%t] %m%n</pattern>
</PatternLayout>
<Policies>
<OnStartupTriggeringPolicy />
<TimeBasedTriggeringPolicy interval="6" modulate="true"/>
<SizeBasedTriggeringPolicy size="250 MB"/>
</Policies>
</RollingFile>
</appenders>
<loggers>
<root level="trace">
<appender-ref ref="MyFileAppender"/>
</root>
</loggers>
</configuration>
It exists in the classpath of the project and I tried putting it in many other directories..
I created a logger in the code like so:
Logger logger = LogManager.getLogger(MyClass.class.getName());
logger.info("test");
And nothing is written and no file is created.
When I debug the code I see that the logger is the default logger(console).

place log4j2.xml file under src/main/resources. It works

Actually This is a straight forward process. Two main classes of Log4j 2 are as follows that you need to import like this:
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
Now get a Logger instance by using this code.
private static final Logger logger = LogManager.getLogger();
Note I didn't specified the class name to getLogger() method as a parameter. Log4j 2 automatically figures it out.
Now you can use any of the info(), trace(), debug(), warn(), error(), fatal() method from the Logger class. But to get the output from all of these methods you'll need a XML configuration file. By default Log4j 2 only produces output from the error() and fatal() methods.
Configuration file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<File name="MyCustomLogFile" fileName="/home/me/mylogfile.log">
<PatternLayout>
<Pattern>%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
</File>
<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="MyCustomLogFile"/>
<!--<AppenderRef ref="Console"/>-->
</Root>
</Loggers>
</Configuration>
Save this file with any name any where. I use Log4j2.xml as name. Now you'll need this file to be put in classpath, which you can do by passing a system property when running the program as follows:
java -Dlog4j.configurationFile=/path/to/xml/configuration/file/Log4j2.xml MyMainClass
And you've done it. Logging will be right away on your console.
Special Notes:
In XML file I've provided 2 appenders: A file and a console. You can see that you just need to uncomment the commented AppenderRef tag to get output in a file instead of console.
You can also provide an environment variable as a system property. Log4j 2 will read the configuration file from the environment variable first and then in -D argument if not found an environment variable.
Have fun with logging. :-)

you should put your log4j2.xml into the classpath.
or set "log4j.configurationFile" system property to force to use your log4j2.xml
Please refer to: http://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration

It exists in the classpath of the project and I tried putting it in
many other directories.
Where exactly? There is often confusion about where "in the classpath" means. It can't just be anywhere. It has to be at the 'top' or the 'default package'.
src
├── main
│   └── java
│   ├── com
│   │   └── example
│   └── log4j2.xml

A tip for eclipse users:
Right click on the project and click "refresh". Make sure you could see the log4j2.xml file in eclipse.
(This solved my problem.)
To be verbose:
You shouldn't add the file to build path.(If you do, eclipse will warn you about this)
The name of this file doesn't appear in '.classpath' file.
I put my log4j2.xml under src/ directory. It works.

I had similar problem. I put the file under src folder and it worked. I did not mention any package name in the log4j2.xml file.

In the documentation of log4j 2: http://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration
"If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath."
but it is not working with classpath. Instead if we keep it in src folder, then it is working.
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>log4j2.xml</param-value>
</context-param>
similar problem is mentioned here : https://issues.apache.org/jira/browse/LOG4J2-357

I had the problem, I tried some solutions, but only this worked to me:
Go to web.xml, and add this parameter:
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>log4j2.xml</param-value>
</context-param>

I'm quite sure that you have to write down the full qualified name of the class whose messages you want to be logged - something like com.application.log4jtest.YourClass. If that doesn't work, try fiddling with the log level.
Also - just as a notice - you can also write
Logger logger = LogManager.getLogger(MyClass.class); // omit .getClass()

I also faced the same problem.I kept my log4j2.xml file in System environment variable.
Variable name : sys_logroot Variable value : D:\user\gouse
and no logs are created for me.
use the system variable-Dlog4j.configurationFile=path/to/log4j2.xmlSee here
This solve my problem

I had the same 'ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.' message over and over. It made me crazy. The log4j2.xml file was placed correctly at src/main/resources, like i did at thousands of projects before.
The solution in my case was to remove <packaging>pom</packaging> from the root pom.xml. packaging pom causes the content of src/main/resources not to be copied to target/classes.
Happy logging for anyone with the same root cause.

Ok, I solved the problem.
I had to specify in the xml the package="myPackage"

Related

Logs get generated when run from IntelliJ but not from local tomcat server

I have a simple spring boot project and I use log4j2 for logging. When I ran my app in IntelliJ I could see my log files got generated in the specified location but when I packaged it as a war file and deployed it in my local tomcat server, no logs were generated. Any idea?
==========edit============================
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<Properties>
<Property name="log.dir">C:\\users\myname\Desktop</Property>
<Property name="app.name">myapp</Property>
</Properties>
<Appenders>
<RollingFile name="fileLogger" fileName="${log.dir}/app-info.log" filePattern="${log.dir}/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="com.myapp.mypackage" level="info" additivity="true">
<appender-ref ref="fileLogger" level="info" />
</Logger>
<Root level="debug" additivity="false">
<appender-ref ref="console" />
</Root>
</Loggers>
</Configuration>
This is not exactly my log4j2 config file but mine is just as simple. I have one rolling file appender and I want to log the app info to it. If I run my app in IntelliJ, the log file will get generated and I can see the logs flowing in.
I tried C:/users/myname/Desktop too, it worked for IntelliJ but not for my local tomcat.
The same path worked for my friend, it generated log file on his desktop, but he couldn't think of any specific configurations that he had done.
I also tried setting log.dir to a bunch of nonsense, and put it in my local tomcat server, it actually ran without errors. So I think tomcat is not looking at my log4j2.xml at all?
=================update============================
Ok, I deleted CATALINA_HOME in environment variables and used another version of tomcat and it worked.
I tried tomcat 8.5, 9.0.30 and 9.0.37.
9.0.30 wouldn't run until I set the CATALINA_HOME environment variable; No logs were generated after I set it.
I deleted 9.0.30 and tried 8.5. I changed CATALINA_HOME, set it to the 8.5 folder, and no logs were generated.
I deleted 9.0.30 and used 9.0.37 instead, deleted all CATALINA_HOME variables, and it worked. Logs were generated.
It is likely that the generation path of the log files is not allowed when running in Tomcat. You should look in Catalina logs.
Ok, I deleted CATALINA_HOME in environment variables and used another version of tomcat and it worked..
Problems with missing log4j configuration are usually related to the application not finding a log4j config file where you think it should find it. You can add the java parameter -Dlog4j.debug=true to get some diagnostics from the application as it searches for a config file. You can also tell it directly to use a particular file with the option -Dlog4j.configuration=file:/<apath>/log4j.properties. Running applications within a container such as tomcat adds a further level of complexity to the searched-locations for the configuration.

How to setup LogBack Configuration

I'm completely new to LogBack, and I'd like to use it. I notice that you can use a Configuration as an XML, but I have no idea how to implement that XML and have Logback use that instead of the default one.
My programs packages are like me.iarekylew00t.a.b and so on. It'll also be compiled into a runnable JAR at the end. How should I go about adding a logback.xml file, without the enduser needing to have it?
Sorry if this is a noob question, but I've been trying to look this up for hours and I can't find anything that clearly tells someone how to go about adding a configuration - most assume you already know how... Thanks. (please be as detailed as possible)
Add a logback.xml in the root of your classpath containing (tune to your needs):
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</encoder>
</appender>
<logger name="some.logger.name" level="INFO"/>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration>
and that's all.
EDIT: usual directory structure:
src/main/java/
some/package/
someClass.java
some/other/package/
someOtherClass.java
src/main/resources/
logback.xml
in the jar:
some/package/
someClass.class
some/other/package/
someOtherClass.class
logback.xml
I had the same issue and resolved it by copying logback.xml to src/main/java - this was the only way I found to make the executable JAR find it and use it.
Since I didn't want to have two (possibly different) config files, I kept the original logback.xml in my src/resources folder (where Eclipse would find it and use it during development) and replaced the one under src/main/java with a symlink. Works well for me.

How to configure Log4J2

I have spent a couple hours now trying to figure this out and am at a complete loss. I find the new configuration process unnecessarily complex.
I have a Servlet with a web.xml file with the following:
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>file:///etc/myApp/log4j2.xml</param-value>
</context-param>
It doesn't seem to have any effect. I am using Tomcat 7.0.42, and I have removed all references to log4j*.jar in the catalina.properties file. The logs in my app are still being sent, but they are just being sent to System.out with none of the formatting I specified.
So, I tried to just do it by hand on my own:
InputStream in =
new FileInputStream(new File("/etc/myApp/log4j2.xml"));
ConfigurationSource source = new ConfigurationSource(in);
ConfigurationFactory factory = new XMLConfigurationFactory();
Configuration configuration = factory.getConfiguration(source);
LoggerContext context = (LoggerContext) LogManager.getContext();
context.start(configuration);
context.updateLoggers();
Logger.getLogger("Test").log(Level.INFO, "This is a logging message.");
First, this seems entirely convoluted. Clearly there exists some code that will search for different files and assume file types based on their extensions via the "log4jConfiguration" property, so why isn't there a LogManger.reconfigure(String) that has the same effect?
Second, this has no effect either. Again, the log is printed to System.out, and none of the requested formatting is being done.
Here is the contents of my log4j2.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<File name="LogFile" fileName="/var/log/myApp/myApp.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %p %c{1.} [%t] %m%n"/>
</File>
</Appenders>
<Loggers>
<Root level="DEBUG">
<AppenderRef ref="Console" level="DEBUG"/>
<AppenderRef ref="LogFile" level="DEBUG"/>
</Root>
</Loggers>
</Configuration>
The output in both cases comes out something like:
Dec 03, 2013 6:06:45 PM test.Test main
INFO: This is a logging message.
Thanks in advance,
John
EDIT: This is actually working. It appears that I was missing, "log4j-jcl-2.0-beta9.jar". Remko Popma's answer works as well, if the "context-param" above is not working.
There are many possible scenarios with webapp logging, which makes configuration more complex than the ideal. Putting the log4j2 jars and the config file in your webapp's classpath should work. Did you see the manual page for log4j2 use in web apps? If the issue remains, please file a log4j2 jira ticket.
The LoggerContextalready has a method setConfigLocation that takes in a URI as parameter. It baffles me why there isn't a similar method that takes an InputStream as parameter. Instead we have to deal with the most convoluted and messy way of loading our log4j2.xml that is not on the classpath.

log file empty when using log4j2

I use log4j2 in my project something like this:
logger.log(Level.ERROR, this.logData);
My configuration file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ERROR" DLog4jContextSelector="org.apache.logging.log4j.core.async.AsyncLoggerContextSelector">
<Appenders>
<!-- Async Loggers will auto-flush in batches, so switch off immediateFlush. -->
<RandomAccessFile name="RandomAccessFile" fileName="C:\\logs\\log1.log" immediateFlush="false" append="false">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern>
</PatternLayout>
</RandomAccessFile>
</Appenders>
<Loggers>
<Root level="error" includeLocation="false">
<AppenderRef ref="RandomAccessFile"/>
</Root>
</Loggers>
It creates my file, I log something to it, but it's still empty. When I trying to delete this file, OS told me that it in use (if app currently working), but even if I stop application, file still empty.
So which settings should I change to make it work correctly?
I suspect that asynchronous logging is not switched on correctly.
As of beta-9 it is not possible to switch on Async Loggers in the XML configuration, you must set the system property Log4jContextSelector to "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector".
The reason you are not seeing anything in the log is that your log messages are still in the buffer and have not been flushed to disk yet. If you switch on Async Loggers the log messages will be flushed to disk automatically.
I share a cleaner and easier solution.
https://stackoverflow.com/a/33467370/3397345
Add a file named log4j2.component.properties to your classpath. This can be done in most maven or gradle projects by saving it in src/main/resources.
Set the value for the context selector by adding the following line to the file.
Log4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
Log4j will attempt to read the system property first. If the system property is null, then it will fall back to the values stored in this file by default.

Getting log4j2 to work with eclipse

I know there is allot of questions been asked on this but i have been trying to get this to work for few day's and i am not any more forward then when i started.
i have tried to use -Dlog4j.configuration=file:/path/to/log4j.properties and -Dlog4j.debug in eclipse vm arguments (under debug & run) and get no output
I have tried to use .properties and .xml but no joy
Tried to put the .xml and .properties files at the root, in the src and in an external folder which i added to my classpath ... still no joy
I think its using another .xml or .properties files in another lib/jar but because i cant get any debug to work i am finding very difficult to track what i am doing wrong here...
any help would be great! below is the code .. only the error message get's printed.
I have download (http://logging.apache.org/log4j/2.x/download.html) and imported into my app the
log4j-api-2.0-beta8.jar
log4j-core-2.0-beta8
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class CucmServMonitor
{
private static final Logger logger = LogManager.getLogger(CucmServMonitor.class.getName())
public static void main(String[] args)
{
logger.error("testing ERROR level");
logger.trace("exiting application");
System.out.println(logger.getName());
}
}
the xml file i am using just now log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="WARN">
<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="debug">
<appender-ref ref="Console"/>
</root>
</loggers>
</configuration>
Manage to figure this one out. The hint was here.
http://pic.dhe.ibm.com/infocenter/wasinfo/v6r0/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-112.htm
I needed to add a "class folder" of where the log4j2.xml was located and then make sure it was at TOP of the list:
Right click on your project and go to properties
Then follow the step shown below. After adding the folder make sure its at the top and then click ok
Or... just create a resources directory like src/test/resources and add the log4j.xml file to that dir and then make that directory a source folder. Then eclipse will automatically copy the file to the the classes dir and there you have it.
1) Create the log4j.properties file inside the root folder
log4j.rootCategory=DEBUG, CONSOLE
# Appender writes to 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{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
2) Modify the code like this
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class CucmServMonitor {
private static final Logger logger = Logger.getLogger(CucmServMonitor.class);
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
logger.error("testing ERROR level");
logger.trace("exiting application");
System.out.println(logger.getName());
}
}
according to Alexis comment, I setup it, but eclipse still can not find log4j2.xml. finally, I solved it by removing the other jars imported, only keep log4j-api and log4j-core. before I imported all the jars downloaded from the Apache website. hope this can help someone.
According to Alexis comment, I setup it, but eclipse still can not find log4j2.xml. finally, I solved it by removing the other jars imported, only keep log4j-api and log4j-core. before I imported all the jars downloaded from the Apache website.
I solved my project for log4j->log4j2 version upgrading.

Categories

Resources