import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; public class MyClass { private static final Logger LOGGER = Logger.getLogger(MyClass.class); public static void main(String[] args) { // Create a new console appender with a pattern layout ConsoleAppender consoleAppender = new ConsoleAppender(new PatternLayout("%d{HH:mm:ss} %-5p [%c{1}] %m%n")); // Add the console appender to the logger LOGGER.addAppender(consoleAppender); // Log an info message LOGGER.info("Hello, World!"); } }
import org.apache.log4j.FileAppender; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; public class MyClass { private static final Logger LOGGER = Logger.getLogger(MyClass.class); public static void main(String[] args) { // Create a new file appender with a pattern layout and a file name FileAppender fileAppender = new FileAppender(); fileAppender.setLayout(new PatternLayout("%d{HH:mm:ss} %-5p [%c{1}] %m%n")); fileAppender.setFile("logfile.log"); // Add the file appender to the logger LOGGER.addAppender(fileAppender); // Log an error message try { int x = 1 / 0; } catch (Exception e) { LOGGER.error("An error occurred", e); } } }This example adds a file appender with a pattern layout to the logger for the MyClass class. The file appender writes log messages to a file called "logfile.log". The logger is then used to log an error message, including the exception that caused the error. The error message should be written to both the console and the log file. Package library: org.apache.log4j