File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed
logging-modules/log4j/src/test
java/com/baeldung/logging/log4j2 Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .baeldung .logging .log4j2 ;
2
+
3
+ import static org .junit .jupiter .api .Assertions .assertTrue ;
4
+
5
+ import java .io .File ;
6
+ import java .io .IOException ;
7
+ import java .nio .file .Files ;
8
+ import java .nio .file .Paths ;
9
+
10
+ import org .apache .log4j .xml .DOMConfigurator ;
11
+ import org .apache .logging .log4j .LogManager ;
12
+ import org .apache .logging .log4j .Logger ;
13
+ import org .apache .logging .log4j .core .config .Configurator ;
14
+ import org .junit .jupiter .api .Test ;
15
+
16
+ public class DynamicFileAppenderUnitTest {
17
+ @ Test
18
+ public void givenLog4j2DynamicFileNameConfig_whenLogToFile_thenFileIsCreated () throws Exception {
19
+ System .setProperty ("log4j.configurationFile" , "src/test/resources/log4j2-dynamic.xml" );
20
+ System .setProperty ("logfilename" , "app-dynamic-log" );
21
+
22
+ Logger logger = LogManager .getLogger (DynamicFileAppenderUnitTest .class );
23
+ String expectedMessage = "This is an ERROR log message to the same file." ;
24
+ logger .error (expectedMessage );
25
+
26
+ File file = new File ("app-dynamic-log.log" );
27
+ assertTrue (file .exists (), "Log file should be created dynamically." );
28
+
29
+ String content = Files .readString (file .toPath ());
30
+ assertTrue (content .contains (expectedMessage ), "Log file should contain the logged message." );
31
+ }
32
+ }
Original file line number Diff line number Diff line change
1
+ <?xml version =" 1.0" encoding =" UTF-8" ?>
2
+ <Configuration status =" WARN" >
3
+ <Appenders >
4
+ <File name =" DynamicFileAppender" fileName =" ${sys:logfilename}.log" >
5
+ <PatternLayout pattern =" %d [%t] %-5level %logger - %msg%n" />
6
+ </File >
7
+ </Appenders >
8
+ <Loggers >
9
+ <Root level =" INFO" >
10
+ <AppenderRef ref =" DynamicFileAppender" />
11
+ </Root >
12
+ </Loggers >
13
+ </Configuration >
You can’t perform that action at this time.
0 commit comments