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.Map;
20
21 /**
22 * PropertySource implementation that uses environment variables as a source.
23 * All environment variables must begin with {@code LOG4J_} so as not to
24 * conflict with other variables. Normalized environment variables follow a
25 * scheme like this: {@code log4j2.fooBarProperty} would normalize to
26 * {@code LOG4J_FOO_BAR_PROPERTY}.
27 *
28 * @since 2.10.0
29 */
30 public class EnvironmentPropertySource implements PropertySource {
31
32 private static final String PREFIX = "LOG4J_";
33 private static final int DEFAULT_PRIORITY = -100;
34
35 @Override
36 public int getPriority() {
37 return DEFAULT_PRIORITY;
38 }
39
40 @Override
41 public void forEach(final BiConsumer<String, String> action) {
42 final Map<String, String> getenv;
43 try {
44 getenv = System.getenv();
45 } catch (final SecurityException e) {
46 // There is no status logger yet.
47 LowLevelLogUtil.logException(
48 "The system environment variables are not available to Log4j due to security restrictions: " + e,
49 e);
50 return;
51 }
52 for (final Map.Entry<String, String> entry : getenv.entrySet()) {
53 final String key = entry.getKey();
54 if (key.startsWith(PREFIX)) {
55 action.accept(key.substring(PREFIX.length()), entry.getValue());
56 }
57 }
58 }
59
60 @Override
61 public CharSequence getNormalForm(final Iterable<? extends CharSequence> tokens) {
62 final StringBuilder sb = new StringBuilder("LOG4J");
63 for (final CharSequence token : tokens) {
64 sb.append('_');
65 for (int i = 0; i < token.length(); i++) {
66 sb.append(Character.toUpperCase(token.charAt(i)));
67 }
68 }
69 return sb.toString();
70 }
71 }
72