Skip to content

Instantly share code, notes, and snippets.

@hopewise
Created September 28, 2023 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hopewise/854efe65f4670146df2608e19b02754b to your computer and use it in GitHub Desktop.
Save hopewise/854efe65f4670146df2608e19b02754b to your computer and use it in GitHub Desktop.
Log4j to log to a file
Using Log4j to log messages to a file involves a few steps:
1. **Add Dependencies**: If you're using Maven or Gradle, you need to add the required dependencies to your build file.
2. **Configure Log4j**: You need to create a Log4j configuration file (like `log4j2.xml`) to specify how logging should be handled, including sending log messages to a file.
3. **Use in Code**: Finally, you use Log4j in your Java code to log messages.
Let's go through each step:
### 1. Add Dependencies
If you're using Maven, add the following dependencies to your `pom.xml`:
```xml
<!-- Log4j API -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.14.1</version>
</dependency>
<!-- Log4j Core (contains actual implementations) -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.14.1</version>
</dependency>
```
Note: Ensure you're using the latest version by checking the Maven repository.
### 2. Configure Log4j
Create a `log4j2.xml` file in your `src/main/resources` directory with the following content:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<File name="FileLogger" fileName="logs/app.log" append="true">
<PatternLayout>
<pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n</pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="FileLogger"/>
</Root>
</Loggers>
</Configuration>
```
This configuration specifies that logs will be written to a file named `app.log` in a `logs` directory. The logging level is set to `info`, meaning all log messages with a level of `info` or higher will be written to the file.
### 3. Use in Code
In your Java code, you can use Log4j as follows:
```java
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class MyClass {
private static final Logger logger = LogManager.getLogger(MyClass.class);
public static void main(String[] args) {
logger.info("This message will be written to the log file!");
logger.error("This is an error message!");
}
}
```
When you run this code, you'll see the log messages written to the `app.log` file in the `logs` directory.
Remember, if you're using a different version of Log4j or if you want to extend and customize your configuration, you might need to adjust the above setup accordingly.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment