Log4j log append to file name dependent on day - config - java

I'm fairly new to log4j and I would like to set up automatic logging of anything output to the console, like errors, or info messages for a web app running on my local server.
How would I set up my xml and/or properties file to do this? What I really am looking for is that each day a new log file be created in a directory (Ex: /mylogs/app-log-01-08-2014.log)
I've begun like this:
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- general application log -->
<appender name="BarLogFile" class="org.apache.log4j.FileAppender">
<param name="File" value="my-changing-file-name.log" /> ->>> how does this change
<param name="Threshold" value="INFO" /> ->>> should INFO be Console here?
</appender>
<logger name="what-goes-here?">
<appender-ref ref="something-here"/>
</logger>
<root>
<level value="INFO"/>
</root>
Also, where in a web project does the xml file go? WEB-INF?
Any help is appreciated.

You are looking for what is known as "daily rolling log files", configuration is shown here. As for the web project, see this answer.
On a side node, you might want to learn about Logback as alternative.

Related

How to Step By Step configure logging in jboss 6.x with Log4j in Java

Hi all I am new to Jboss so I am get confused while setting up an logging in Jboss 6.1 what I does
I have download and extract the Jboss (jboss-eap-6.1) on my machine then I follow the steps given in this article but still I not able to see the logging on console or in file
the I google it around and come to know that I have to write jboss-deployment-structure.xml file under /META-INF/ folder and have to add -Dorg.jboss.as.logging.per-deployment=false to the start-up of the server (which I dont know where I have to set this) from this link
so can any one give me steps to configure logging in jboss 6.x with Log4j or any logging like java.util.logging to log statements on console or in file thanks.
You should find the standalone.bat file into the /bin folder of Jboss, then you should edit this file, finding the next line
rem Setup JBoss specific properties
set JAVA_OPTS=-Dprogram.‌​name=%PROGNAME% %JAVA_OPTS%
And replace for this
set "JAVA_OPTS= -Dorg.jboss.as.logging.per-deployment=false"
If you want logging
a. you want to use your own "log4j.jar" place it in lib folder
b. place jboss-deployment-structure.xml in META-INF folder
c. Add log4j.xml in WEB-INF/classes
of your application.
Add this in jboss-deployment-structure.xml
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
<deployment>
<exclusions>
<module name="org.apache.log4j" />
</exclusions>
</deployment>
</jboss-deployment-structure>
Add this in log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="appender" class="org.apache.log4j.FileAppender">
<param name="File" value="${jboss.server.log.dir}/server.log"/>
<param name="Append" value="true"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %p - %m%n"/>
</layout>
</appender>
<root>
<priority value ="trace"/>
<appender-ref ref="appender"/>
</root>
</log4j:configuration>
Then you can see logging on console....

How to make isInfoEnabled disabled in Log4J XML configuration

I have various log files (debug, error) and different configurations (e.g. dev, prod). In dev I'd like to have everything logged into my debug.log and errors written to error.log. However in production I'd like to switch the debug logging off. Right now I'm using this config:
<appender name="FileAppender" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="/logs/debug.log" />
<param name="Append" value="true" />
<param name="Threshold" value="OFF" />
...
So it will decide whether to write or not itself. But I'd like to check in the code sometimes, if the logger writes to log:
if(logger.isInfoEnabled()) {};
Even the threshold is set to 'OFF' it does says, that info is enabled.
What I'm trying to do is to configure the XML, so it would not only skip writing to the debug.log in the production, but also it would set the infoEnabled value to false, so I could use it in my code. Is there are any possibilities to do that?
Thanks in advance!
Configure your ROOT logger to 'WARN' level. In Log4J 1.x:
<root>
<level value="WARN" />
</root>
In Log4J 2.x:
<root level="WARN">
</root>

Log file not produced until WebLogic is restarted

I'm working on the development of an application that is deployed on WebLogic 10.3. It is packaged as an EAR and includes one module. The application works fine by itself but I am faced with issue related to logging.
I am using Log4j. The library is included in the EAR file and log4j.xml is placed under JAR module. So the config location is the following:
A.ear/B.jar/log4j.xml
Log4j config is following:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="CA" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{dd-MMM-yyyy-HH:mm:ss} %p %C{1} - %m%n" />
</layout>
</appender>
<appender name="DRFA" class="org.apache.log4j.DailyRollingFileAppender">
<param name="file"
value="servers/AdminServer/logs/EJB.log" />
<param name="Append" value="true" />
<param name="DatePattern" value="'-'yyyy-MM-dd" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{dd-MMM-yyyy-HH:mm:ss} %p %C{1} - %m%n" />
</layout>
</appender>
<logger name="com.companyname.ejb" additivity="false">
<level value="DEBUG" />
<appender-ref ref="DRFA" />
<appender-ref ref="CA" />
</logger>
<logger name="com.companyname.results" additivity="false">
<level value="DEBUG" />
<appender-ref ref="DRFA" />
<appender-ref ref="CA" />
</logger>
<logger name="com.companyname.marketdata" additivity="false">
<level value="DEBUG" />
<appender-ref ref="DRFA" />
<appender-ref ref="CA" />
</logger>
<root>
<level value="DEBUG" />
<appender-ref ref="CA" />
</root>
When I build and deploy EAR (using Maven and customized WebLogic plugin) and call application no log file appears. But if I restart WebLogic everything is fine.
WebLogic is running under Windows 7 in domain mode with single node.
I'd like to know if there is some way to make the log appear without weblogic restart (since it can cause issues on production environment)?
Update: Also I'd like to know what is the reason of such behavior (i.e. why the log file is not created right after application deployment)? Is this an issue with Weblogic, log4j or with their coupling? I've tried to find the answer in the Oracle documentation, but no luck for now.
Some notes:
In prod environment, you probably want to have your log configuration outside app packages, so you can change log levels without redeployment.
You should plan for production to be able to handle restarts. We usually have hot and cold servers, so load can be balanced and servers restarted when doing the deployment.
About the issue, if you want to, you could specify a servlet that is run on startup of app and configures your log4j. Something like:
web.xml
<servlet>
<servlet-name>SomeServlet</servlet-name>
<servlet-class>YourServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
Servlet
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.xml.DOMConfigurator;
public class YourServlet extends HttpServlet
{
#Override
public void init(final ServletConfig config)
throws ServletException
{
final java.net.URL url = Thread.currentThread().getContextClassLoader()
.getResource("Log4j.xml");
DOMConfigurator.configure(url);
}
}
There's also an example on the web about using a servlet context listener.
Edit. as to why this happens, weblogic logging mechanism is initiated by default on startup with these kind of settings:
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dlog4j.configuration=file:<path>/log4j.properties
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dweblogic.log.Log4jLoggingEnabled=true
so if you just redeploy your app without restarting the server, these settings will not be used -> logging will not get initiated.
I didn't found any quick configuration solution, so code change was required.
I've added Weblogic Application Lifecycle listener as suggested here. Its postStart() method initializes log4j explicitly through DOMConfigurator and now logs appear right after application deployment.
The are few alternatives how configuration can be initialized. One of them was mentioned in eis' post and another here. But I've choose listener in order to keep single module in EAR and in order to avoid issues with singleton EJB on cluster environment (i.e. I am not sure if Weblogic will create singleton on each node or just one instance per cluster).
Also in order to prevent environment changes for local and dev environment, I am using internal log4j.xml (i.e. placed within ear file) there.
For stage and prod - external config file is specified (in Maven profile).
External file is monitored by log4j so changes will be automatically applied without any redeployments or restarts.

What is the best way to use log4j in the web application?

We are starting a Spring MVC based web application. We will be using tomcat as the web server.
I need to configure log4j in the application and log to the application specific file and not to the tomcat log files.
e.g. tomcat has its own log files like localhost.log etc. I want something like myAppName.log in the tomcats log folder.
The logging configuration will go in lo4j.xml or log4j.properties in the application war file.
Plus I dont want to hard code the output log file in the web application.
But I am not sure how to do this.
Please help me. As well correct me if I am wrong somewhere.
Do like this, initialize the logger with following code,
Logger log = Logger.getLogger(this.getClass());
log the information like follows,
log.debug("My message");
and place the log4j.xml in your class path. content like follows,
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="infoLogsFile" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="MyApplication.log"/>
<param name="Threshold" value="DEBUG"/>
<param name="MaxFileSize" value="100MB"/>
<param name="ImmediateFlush" value="TRUE"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
</layout>
</appender>
<root>
<priority value ="DEBUG" />
<appender-ref ref="infoLogsFile"/>
</root>
</log4j:configuration>
Do not forget to add the required jars like log4jXXX.jars and apache common logging jars. with this you will be able to see all log messages in MyApplication.log file creates in bin folder of your tomcat.
Try this:
Put the log4j jar as part of the web application
Do not put a configuration as part of your web application
Create your log4j.xml wherever you like
When you start tomcat provide this argument
-Dlog4j.configuration=file:///.../log4j.xml

Creating multiple log files of different content with log4j

Is there a way to configure log4j so that it outputs different levels of logging to different appenders?
I'm trying to set up multiple log files. The main log file would catch all INFO and above messages for all classes. (In development, it would catch all DEBUG and above messages, and TRACE for specific classes.)
Then, I would like to have a separate log file. That log file would catch all DEBUG messages for a specific subset of classes, and ignore all messages for any other class.
Is there a way to get what I'm after?
This should get you started:
log4j.rootLogger=QuietAppender, LoudAppender, TRACE
# setup A1
log4j.appender.QuietAppender=org.apache.log4j.RollingFileAppender
log4j.appender.QuietAppender.Threshold=INFO
log4j.appender.QuietAppender.File=quiet.log
...
# setup A2
log4j.appender.LoudAppender=org.apache.log4j.RollingFileAppender
log4j.appender.LoudAppender.Threshold=DEBUG
log4j.appender.LoudAppender.File=loud.log
...
log4j.logger.com.yourpackage.yourclazz=TRACE
Perhaps something like this?
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- general application log -->
<appender name="MainLogFile" class="org.apache.log4j.FileAppender">
<param name="File" value="server.log" />
<param name="Threshold" value="INFO" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/>
</layout>
</appender>
<!-- additional fooSystem logging -->
<appender name="FooLogFile" class="org.apache.log4j.FileAppender">
<param name="File" value="foo.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/>
</layout>
</appender>
<!-- foo logging -->
<logger name="com.example.foo">
<level value="DEBUG"/>
<appender-ref ref="FooLogFile"/>
</logger>
<!-- default logging -->
<root>
<level value="INFO"/>
<appender-ref ref="MainLogFile"/>
</root>
</log4j:configuration>
Thus, all info messages are written to server.log; by contrast, foo.log contains only com.example.foo messages, including debug-level messages.
I had this question, but with a twist - I was trying to log different content to different files. I had information for a LowLevel debug log, and a HighLevel user log. I wanted the LowLevel to go to only one file, and the HighLevel to go to both a file, and a syslogd.
My solution was to configure the 3 appenders, and then setup the logging like this:
log4j.threshold=ALL
log4j.rootLogger=,LowLogger
log4j.logger.HighLevel=ALL,Syslog,HighLogger
log4j.additivity.HighLevel=false
The part that was difficult for me to figure out was that the 'log4j.logger' could have multiple appenders listed. I was trying to do it one line at a time.
Hope this helps someone at some point!
For the main logfile/appender, set up a .Threshold = INFO to limit what is actually logged in the appender to INFO and above, regardless of whether or not the loggers have DEBUG, TRACE, etc, enabled.
As for catching DEBUG and nothing above that... you'd probably have to write a custom appender.
However I'd recommend not doing this, as it sounds like it would make troubleshooting and analysis pretty hard:
If your goal is to have a single file where you can look to troubleshoot something, then spanning your log data across different files will be annoying - unless you have a very regimented logging policy, you'll likely need content from both DEBUG and INFO to be able to trace execution of the problematic code effectively.
By still logging all of your debug messages, you are losing any performance gains you usually get in a production system by turning the logging (way) down.
Demo link: https://github.com/RazvanSebastian/spring_multiple_log_files_demo.git
My solution is based on XML configuration using spring-boot-starter-log4j. The example is a basic example using spring-boot-starter and the two Loggers writes into different log files.

Categories

Resources