Hi everyone! Today I brought you something different. This is based on Java.. As a introduction, I can explain it in this way. If you ever run a web server by yourself? I think you have done it..You can see after the server starts, it prints something on the console in your IDE or terminal. It LOGS your activities! All the actions you participate, are logged for tracking. So, how to achieve this using a code? Here I explain the way in Java. Not pure java, but Spring Boot. Since it's the most used Java EE framework for web applications done in java.

Let's start the work!


Step 1 - Create a Spring Boot project with intelliJ IDEA


What you have to do is click on File > new > project. Then follow the steps shown below.





When you click on finish, the project will be built and ready for use. You can give any name, when you name the project. It's should not be as same as my one. You can run the project and check whether it is started or not on port 8080.


Step 2 - Include the Log4J class into the project


Look at the files in the project folder There is a file called pom.xml. It's the file responsible for keeping the necessary dependencies for the project. So we have to add a Maven dependency for Log4J class.
Add this code within the tag <dependencies>.

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

IDE will track a change in pom file. Then it asks for import changes. Do it! Now you are able to use Log4J class.


Step 3 - Create a controller


In your project, navigate to this package. src > main > java > your package
Right click on it and create a new Java class. Here I will name it as LoggingController.

We need to register an end point(request mapping) to perform a request with the server. So, I try to return a simple "hello" with the end point "/logs". The path for end point on the browser will be : http://localhost:8080/logs

Then we have to import our Logger to the controller file. Create a instance from Logger class and assign it in this way. You need to do this in every file you want to use Logger!
Logger logger = Logger.getLogger(this.getClass());

Full code for controller: LoggingController.java

package com.log4j.logger.controllers;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin
@RequestMapping
public class LoggingController {

    Logger logger = Logger.getLogger(this.getClass());

    @RequestMapping(value = "/logs", method = RequestMethod.GET)
    public String performGet() {
        logger.info("Request Sent");
        logger.error("Error Occured");
        return "hello";
    }

}


Step 4 - Define the Log4j properties


This is the most important step! You have to introduce your configuration to the project. Where to do it? Find this package. src > main > resources
Create a new file called log4j.properties in it. Name must be log4j.


log4j.rootLogger=INFO, CONSOLE, FILE

#Properties for Console
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.conversionPattern=%d [%p] %c - %m%n

#Properties for Log File
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.File=logs/log.txt
log4j.appender.FILE.ImmediateFlush=true
log4j.appender.FILE.Threshold=debug
log4j.appender.FILE.Append=true
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%d [%-5p] %c - %m%n
log4j.appender.FILE.MaxFileSize=1MB

You can see a lot of configurations here. Could you understand? Let me explain!

log4j.rootLogger=INFO, CONSOLE, FILE
Our project need a root level of logging to be started! Those levels are INFO, DEBUG, ERROR and so on..INFO is the way it logs to the user. So I use this level as root level. Then you see CONSOLE and FILE words. What are they? They are for console and log file. I configure separate properties for both of them. FILE means the file I'm going to write the logs in it. Then we use these two words for properties.

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
Appender of logs for the console

log4j.appender.CONSOLE.Target=System.out
Where to print the logs. As a System Out, it will print on the console itself.

log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
The pattern class responsible for formatting the patterns

log4j.appender.CONSOLE.layout.conversionPattern=%d [%p] %c - %m%n
The pattern you want to log your activities on the console. There are a lot of ways to format your pattern. I prefer to use this way.
d for date, p for log category, c for source, m for log message and n for new line.
If you want more details, this article will be a great help

log4j.appender.FILE=org.apache.log4j.RollingFileAppender
Appender for the logging file

log4j.appender.FILE.File=logs/log.txt
Path for the text file that writes all the logs. This will be created in project folder within a new folder called logs.

log4j.appender.FILE.ImmediateFlush=true
Set the immediate flush to true (default). If set to true, it is delivered after each method call. By default, it is set to true. Below we will cover a classic example.

log4j.appender.FILE.Threshold=debug
Put a limit for Debug mode.

log4j.appender.FILE.Append=true
Set TRUE for appending the logs into the TEXT file. This will append all the logs. It it's set to FALSE, logs will be overwritten after each method call.

log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
The pattern class responsible for formatting the patterns

log4j.appender.FILE.layout.conversionPattern=%d [%-5p] %c - %m%n
The pattern you want to log your activities in the file.

log4j.appender.FILE.MaxFileSize=1MB
Max file size for log text file. If it reached the max size, then it automatically creates a new file with the name as log1.txt. This will continue..

I think now you have the understanding of these log4j properties. I have explained all the things!


Step 5 - Perform a Request


Simply go to the URL from your browser - http://localhost:8080/logs
Now the log messages you defined in the logic for this end point, will be on the console and written into the file.

Console:



Log File:



That'all for today guys! Is it difficult? Not at all.. This is the easiest way to log your activities with the logic for your files. You can implement it as you want! This is just for an introduction. Try this with your Java project!

Good Bye!






0 Comments