View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.util;
18  
19  import java.util.Objects;
20  import java.util.Properties;
21  
22  /**
23   * PropertySource backed by the current system properties. Other than having a
24   * higher priority over normal properties, this follows the same rules as
25   * {@link PropertiesPropertySource}.
26   *
27   * @since 2.10.0
28   */
29  public class SystemPropertiesPropertySource implements PropertySource {
30  
31  	private static final int DEFAULT_PRIORITY = 100;
32  	private static final String PREFIX = "log4j2.";
33  
34  	@Override
35  	public int getPriority() {
36  		return DEFAULT_PRIORITY;
37  	}
38  
39  	@Override
40  	public void forEach(final BiConsumer<String, String> action) {
41  		Properties properties;
42  		try {
43  			properties = System.getProperties();
44  		} catch (final SecurityException e) {
45  			// (1) There is no status logger.
46  			// (2) LowLevelLogUtil also consults system properties ("line.separator") to
47  			// open a BufferedWriter, so this may fail as well. Just having a hard reference
48  			// in this code to LowLevelLogUtil would cause a problem.
49  			// (3) We could log to System.err (nah) or just be quiet as we do now.
50  			return;
51  		}
52  		// Lock properties only long enough to get a thread-safe SAFE snapshot of its
53  		// current keys, an array.
54  		final Object[] keySet;
55  		synchronized (properties) {
56  			keySet = properties.keySet().toArray();
57  		}
58  		// Then traverse for an unknown amount of time.
59  		// Some keys may now be absent, in which case, the value is null.
60  		for (final Object key : keySet) {
61  			final String keyStr = Objects.toString(key, null);
62  			action.accept(keyStr, properties.getProperty(keyStr));
63  		}
64  	}
65  
66  	@Override
67  	public CharSequence getNormalForm(final Iterable<? extends CharSequence> tokens) {
68  		return PREFIX + Util.joinAsCamelCase(tokens);
69  	}
70  
71  }