P15GEN2\59518
2024-05-29 d4210c7c4b04abde20037ea8aa0f54ef8a2649aa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package foundation.log;
 
import java.io.File;
import java.io.FileInputStream;
 
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
 
public class LogCenter {
 
    private static LoggerContext context;
    private static Configuration configuration;
    
    public static void initConsole(String path) throws Exception {
        File file = new File(path);
        
        if (!file.exists()) {
            throw new Exception("log config not exists: " + file);
        }
        
        FileInputStream inputStream = new FileInputStream(file);
        try {
            ConfigurationSource source = new ConfigurationSource(inputStream);
            context = Configurator.initialize(null, source);
            configuration = context.getConfiguration();
        }
        finally {
            inputStream.close();
        }
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void appendOneLogger() {
        Layout layout = PatternLayout.createDefaultLayout(configuration);
        
        @SuppressWarnings("deprecation")
        Appender appender = FileAppender.createAppender("target/test.log", "false", "false", "File", "true", "false", "false", "4000", layout, null, "false", null, configuration);
        appender.start();
        configuration.addAppender(appender);
        
        AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
        AppenderRef[] refs = new AppenderRef[] {ref};
        
        LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, "org.apache.logging.log4j", "true", refs, null, configuration, null);
        loggerConfig.addAppender(appender, null, null);
        
        configuration.addLogger("org.apache.logging.log4j", loggerConfig);
        context.updateLoggers();        
    }
 
}