001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017package org.apache.logging.log4j.util; 018 019import java.util.Objects; 020import java.util.Properties; 021 022/** 023 * PropertySource backed by the current system properties. Other than having a 024 * higher priority over normal properties, this follows the same rules as 025 * {@link PropertiesPropertySource}. 026 * 027 * @since 2.10.0 028 */ 029public class SystemPropertiesPropertySource implements PropertySource { 030 031 private static final int DEFAULT_PRIORITY = 100; 032 private static final String PREFIX = "log4j2."; 033 034 @Override 035 public int getPriority() { 036 return DEFAULT_PRIORITY; 037 } 038 039 @Override 040 public void forEach(final BiConsumer<String, String> action) { 041 Properties properties; 042 try { 043 properties = System.getProperties(); 044 } catch (final SecurityException e) { 045 // (1) There is no status logger. 046 // (2) LowLevelLogUtil also consults system properties ("line.separator") to 047 // open a BufferedWriter, so this may fail as well. Just having a hard reference 048 // in this code to LowLevelLogUtil would cause a problem. 049 // (3) We could log to System.err (nah) or just be quiet as we do now. 050 return; 051 } 052 // Lock properties only long enough to get a thread-safe SAFE snapshot of its 053 // current keys, an array. 054 final Object[] keySet; 055 synchronized (properties) { 056 keySet = properties.keySet().toArray(); 057 } 058 // Then traverse for an unknown amount of time. 059 // Some keys may now be absent, in which case, the value is null. 060 for (final Object key : keySet) { 061 final String keyStr = Objects.toString(key, null); 062 action.accept(keyStr, properties.getProperty(keyStr)); 063 } 064 } 065 066 @Override 067 public CharSequence getNormalForm(final Iterable<? extends CharSequence> tokens) { 068 return PREFIX + Util.joinAsCamelCase(tokens); 069 } 070 071}