Ask Sawal

Discussion Forum
Notification Icon1
Write Answer Icon
Add Question Icon

where log4j log file created?

4 Answer(s) Available
Answer # 1 #

This article is a tutorial about logging to files in specific location. We will first checkout other logging methods and then proceed to log to a specific location.

Log4J(Java) is the widely used logging framework for Java. It continues to grow continuously with recent upgrade of Log4j2. Log4j helps to log files to a file or console or even to a database. Log4j has three basic components to support logging – Logger, Appender and Layouts.

Logger carries out the logging activity and is the interaction point for the application. It is used to specify logging mode, name for the logger and delivers  logs to logging destination with the help of appender. Log4j supports multiple predefined appenders and supports creating custom appenders. Appender does the heavylifting in log4j connecting the logger to destination with the mode specified.

Layout specifies the display format of the logs. Commonly used Layout for Log4j is PatternLayout. A sample pattern is  %d %-5p (%F: %L) – %m%n. The format strings  for the pattern are as follows:

We will see first an example of logging to console. This is much similar to using  System.out.println. The differentiator is the ability of Log4j to support logging mode and suppress log messages below the specified threshold.

Console logs do not survive application restarts. In Production grade applications, log files need to be preserved for future analysis. This is achieved by using a file logger which is similar to console logger but it just logs to a specific file rather than console. Below we will see a simple configuration for logging to a file without location specification.

The above configuration represents a DailyRollingFileAppender. This logs the output to a specific file example.log. File is created under the application’s running directory. Appender rotates the log file on daily basis. Application directories are cleared during consecutive deploy. Hence it does not alleviate the concerns of the previous approach.

Recommended approach is to log files to a specific location in the deployed environment. This is easily achieved by extending our previous example. We just need to provide the location under the File property.

The key thing to lookout is the file location has been specified for the File property. This controls the location of the output and ensures log files are backed up for future inspection.

Java Logger Class

Candice Bindu
Answer # 2 #

Logging is a critical feature of any application. In this tutorial we will cover some log4j best practices that can help you get started and improve how you do logging with log4j.

A logging framework is important for any Java/J2EE based application. By changing the configuration, you can easily write your logs to different places. You can write your Java application logs to a database, files on the disk, a log management system, a console, Syslog or possibly other places in the network without changing your application code.

When you declare any variable in your code, it comes with overhead. You can overcome this overhead by declaring the static Logger reference as shown below. If you invoke constructors on the LogManager object then it will consume a lot of CPU and if you declare it as static then you will not have to hard code the class type which will save CPU cycles.

There could be scenarios when you can face problems with a specific appender, or get into issues while working with it. You can resolve these issues after enabling the internal debugging by setting the log4j.debug system property in the configuration file. You can also add -Dlog4j.debug to the JVM system variables to enable log4j’s own internal debug logging as shown below.

You can directly persist logs details into your database by simply creating a table (shown below) in a database (here oracle) and setting the JDBCAppender configuration into file (shown below). When you persist logs into database and try to search those logs through queries in SQL then it becomes very difficult to get the expected search result when you log any real volume. It is advisable to send the logs to a log management service or write them into a file which can provide full-text indexing and more functionality with logs.

You can use SMTPAppender to notify the exceptions in the logs to the required stakeholders through emails. But you do not need to send every exception thrown by the application through emails as it may stall the smooth operation of your application as the system may get busy in sending emails. There could be scenarios when you will see emails bursting for lots of recurring exceptions which may result into more errors at the application level which may impact its performance very badly. Therefore, select the critical exceptions only by changing the log level to FATAL, or ERROR, etc. in order to send only the required logging information through emails as shown below. This will not only provide the meaningful information but also there will be no impact on our application performance.

You can use the error tracking product in order to send alerts about exceptions thrown by your application by using NTEventLogAppender. Such a product can also dedupe the errors so you can figure out when an error is truly new, track its history, and track error rates. The configuration file of log4j’s NTEventLogAppender for ActiveMQ events will look as shown below.

You can capture application logs and write them to a file on a disk which could be compressed and archived periodically. But when you want to search through the logs across multiple servers and applications then you need to send all of our logs to a central repository. There are a lot of log management solutions that can help you with this, or you can even setup your own elastic search cluster for it. My suggestion is to use Splunk which provides fast, Google search engine like searching functionalities across bulky terabytes of logs. You can easily filter the logs by log level or date which makes it easy to correlate into transactions of multiple related log events, etc.

You can use filters which can be configured to suppress specific log messages. The following is the configuration details for to set up filters in order to suppress certain logging statements.

If you want to do something that the standard Appenders do not support, you can either search online or write your own customized Appender. For example, you can make your own custom log4j appender by extending the AppenderSkeleton class. It provides the code for common functionality, such as support for threshold filtering and support for general filters and you can add your functionality on top of it by method overriding as shown below.

You can modify your configuration file in order to change the pattern layouts format for the fields which you are throwing as output.

You can log custom fields like username, etc. which can help you to provide additional context information about the user, customer or transaction related to the log statements. In log4j, you can use NDC class which is known as per-thread stack of context labels. The labels which are pushed on this stack can be displayed in a PatternLayout by specifying the %x or the %ndc format parameter as shown below.

Additionally, you can assign objects in contexts to use what it calls “active property values.” When the log message is written to a file or console, the ‘toString ()’ method will be called which can dynamically do something.

By default, you can log an object to it and it will serialize it with its default renderers. If you want to really get the value of the structured logging, you will want to send your logs to a log management tool that can index all the fields and enable powerful searching and analytics capabilities. You can also use MulticolorLayout class along with log4j’s ConsoleAppender to get multiple colors in logs (i.e. to view logs into distinct colors) for which you need to append the following maven repository and dependency.

Next, you have to set the related configuration details in files as shown below.

Be sure to use proper logging levels within your code. One of the big advantages of using a logging framework is being able to turn up or down the verbosity of your logging at any time. Don’t log everything as Debug. Be sure to think about what information will be helpful later when you are troubleshooting application problems. You have to balance how much logging is noise versus surfacing critical problems.

You can specify in your log4j properties which log4j logging levels you want to log. You can use this to send all logs to a file on disk, but perhaps only fatal problems to a database or other appender.

log4j levels:

Bharani Raymond
Answer # 3 #

To write your logging information into a file, you would have to use org.apache.log4j.FileAppender.

FileAppender has the following configurable parameters:

Following is a sample configuration file for FileAppender −

If you wish to have an XML configuration file equivalent to the above file, then here is the content:

You can try log4j - Sample Program with the above configuration.

You may want to write your log messages into multiple files for certain reasons, for example, if the file size reached to a certain threshold.

To write your logging information into multiple files, you would have to use org.apache.log4j.RollingFileAppender class which extends the FileAppender class and inherits all its properties.

We have the following configurable parameters in addition to the ones mentioned above for FileAppender −

Following is a sample configuration file for RollingFileAppender.

If you wish to have an XML configuration file, you can generate the same as mentioned in the initial section and add only additional parameters related to RollingFileAppender.

This example configuration demonstrates that the maximum permissible size of each log file is 5 MB. Upon exceeding the maximum size, a new log file will be created. Since maxBackupIndex is defined as 2, once the second log file reaches the maximum size, the first log file will be erased and thereafter, all the logging information will be rolled back to the first log file.

You can try log4j - Sample Program with the above configuration.

There may be a requirement to generate your log files on a daily basis to keep a clean record of your logging information.

To write your logging information into files on a daily basis, you would have to use org.apache.log4j.DailyRollingFileAppender class which extends the FileAppender class and inherits all its properties.

There is only one important configurable parameter in addition to the ones mentioned above for FileAppender:

DatePattern controls the rollover schedule using one of the following patterns:

Following is a sample configuration file to generate log files rolling over at midday and midnight of each day.

If you wish to have an XML configuration file, you can generate the same as mentioned in the initial section and add only additional parameters related to DailyRollingFileAppender.

You can try log4j - Sample Program with the above configuration.

Muhammad Jay
Answer # 4 #
  • Create a Java Project. Open the MyEclipse and go to File->New-> Java Project.
  • Add the log4j jar File.
  • Create a Java File.
  • Create a File.
  • Add the file to the Classpath.
  • Compile and Run the Project.
afdbq Salman