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.io.File;
20  import java.io.IOException;
21  import java.lang.reflect.Method;
22  
23  /**
24   * @Since 2.9
25   */
26  public class ProcessIdUtil {
27  
28      public static final String DEFAULT_PROCESSID = "-";
29  
30      public static String getProcessId() {
31          try {
32              // LOG4J2-2126 use reflection to improve compatibility with Android Platform which does not support JMX extensions
33              final Class<?> managementFactoryClass = Class.forName("java.lang.management.ManagementFactory");
34              final Method getRuntimeMXBean = managementFactoryClass.getDeclaredMethod("getRuntimeMXBean");
35              final Class<?> runtimeMXBeanClass = Class.forName("java.lang.management.RuntimeMXBean");
36              final Method getName = runtimeMXBeanClass.getDeclaredMethod("getName");
37  
38              final Object runtimeMXBean = getRuntimeMXBean.invoke(null);
39              final String name = (String) getName.invoke(runtimeMXBean);
40              //String name = ManagementFactory.getRuntimeMXBean().getName(); //JMX not allowed on Android
41              return name.split("@")[0]; // likely works on most platforms
42          } catch (final Exception ex) {
43              try {
44                  return new File("/proc/self").getCanonicalFile().getName(); // try a Linux-specific way
45              } catch (final IOException ignoredUseDefault) {
46                  // Ignore exception.
47              }
48          }
49          return DEFAULT_PROCESSID;
50      }
51  }