summaryrefslogtreecommitdiff
path: root/core/src/main/java/org/elasticsearch/common/logging/LogConfigurator.java
blob: b29cab9fbfe2ab031943127cf3d18e82b632d8a5 (plain)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.elasticsearch.common.logging;

import org.apache.log4j.PropertyConfigurator;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsException;
import org.elasticsearch.env.Environment;

import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.common.Strings.cleanPath;

/**
 * Configures log4j with a special set of replacements.
 */
public class LogConfigurator {

    static final List<String> ALLOWED_SUFFIXES = Arrays.asList(".yml", ".yaml", ".json", ".properties");

    private static final Map<String, String> REPLACEMENTS;
    static {
        Map<String, String> replacements = new HashMap<>();
        // Appenders
        replacements.put("async", "org.apache.log4j.AsyncAppender");
        replacements.put("console", ConsoleAppender.class.getName());
        replacements.put("dailyRollingFile", "org.apache.log4j.DailyRollingFileAppender");
        replacements.put("externallyRolledFile", "org.apache.log4j.ExternallyRolledFileAppender");
        replacements.put("extrasRollingFile", "org.apache.log4j.rolling.RollingFileAppender");
        replacements.put("file", "org.apache.log4j.FileAppender");
        replacements.put("jdbc", "org.apache.log4j.jdbc.JDBCAppender");
        replacements.put("jms", "org.apache.log4j.net.JMSAppender");
        replacements.put("lf5", "org.apache.log4j.lf5.LF5Appender");
        replacements.put("ntevent", "org.apache.log4j.nt.NTEventLogAppender");
        replacements.put("null", "org.apache.log4j.NullAppender");
        replacements.put("rollingFile", "org.apache.log4j.RollingFileAppender");
        replacements.put("smtp", "org.apache.log4j.net.SMTPAppender");
        replacements.put("socket", "org.apache.log4j.net.SocketAppender");
        replacements.put("socketHub", "org.apache.log4j.net.SocketHubAppender");
        replacements.put("syslog", "org.apache.log4j.net.SyslogAppender");
        replacements.put("telnet", "org.apache.log4j.net.TelnetAppender");
        replacements.put("terminal", TerminalAppender.class.getName());

        // Policies
        replacements.put("timeBased", "org.apache.log4j.rolling.TimeBasedRollingPolicy");
        replacements.put("sizeBased", "org.apache.log4j.rolling.SizeBasedTriggeringPolicy");

        // Layouts
        replacements.put("simple", "org.apache.log4j.SimpleLayout");
        replacements.put("html", "org.apache.log4j.HTMLLayout");
        replacements.put("pattern", "org.apache.log4j.PatternLayout");
        replacements.put("consolePattern", "org.apache.log4j.PatternLayout");
        replacements.put("enhancedPattern", "org.apache.log4j.EnhancedPatternLayout");
        replacements.put("ttcc", "org.apache.log4j.TTCCLayout");
        replacements.put("xml", "org.apache.log4j.XMLLayout");
        REPLACEMENTS = unmodifiableMap(replacements);
    }

    private static boolean loaded;

    /**
     * Consolidates settings and converts them into actual log4j settings, then initializes loggers and appenders.
     *  @param settings      custom settings that should be applied
     * @param resolveConfig controls whether the logging conf file should be read too or not.
     */
    public static void configure(Settings settings, boolean resolveConfig) {
        if (loaded) {
            return;
        }
        loaded = true;
        // TODO: this is partly a copy of InternalSettingsPreparer...we should pass in Environment and not do all this...
        Environment environment = new Environment(settings);

        Settings.Builder settingsBuilder = Settings.builder();
        if (resolveConfig) {
            resolveConfig(environment, settingsBuilder);
        }

        // add custom settings after config was added so that they are not overwritten by config
        settingsBuilder.put(settings);
        settingsBuilder.replacePropertyPlaceholders();
        Properties props = new Properties();
        for (Map.Entry<String, String> entry : settingsBuilder.build().getAsMap().entrySet()) {
            String key = "log4j." + entry.getKey();
            String value = entry.getValue();
            value = REPLACEMENTS.getOrDefault(value, value);
            if (key.endsWith(".value")) {
                props.setProperty(key.substring(0, key.length() - ".value".length()), value);
            } else if (key.endsWith(".type")) {
                props.setProperty(key.substring(0, key.length() - ".type".length()), value);
            } else {
                props.setProperty(key, value);
            }
        }
        // ensure explicit path to logs dir exists
        props.setProperty("log4j.path.logs", cleanPath(environment.logsFile().toAbsolutePath().toString()));
        PropertyConfigurator.configure(props);
    }

    /**
     * sets the loaded flag to false so that logging configuration can be
     * overridden. Should only be used in tests.
     */
    static void reset() {
        loaded = false;
    }

    static void resolveConfig(Environment env, final Settings.Builder settingsBuilder) {

        try {
            Set<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
            Files.walkFileTree(env.configFile(), options, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    String fileName = file.getFileName().toString();
                    if (fileName.startsWith("logging.")) {
                        for (String allowedSuffix : ALLOWED_SUFFIXES) {
                            if (fileName.endsWith(allowedSuffix)) {
                                loadConfig(file, settingsBuilder);
                                break;
                            }
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException ioe) {
            throw new ElasticsearchException("Failed to load logging configuration", ioe);
        }
    }

    static void loadConfig(Path file, Settings.Builder settingsBuilder) {
        try {
            settingsBuilder.loadFromPath(file);
        } catch (SettingsException | NoClassDefFoundError e) {
            // ignore
        }
    }
}