View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.util;
15  
16  import java.net.InetAddress;
17  import java.net.UnknownHostException;
18  import java.util.Iterator;
19  import java.util.Properties;
20  
21  import ch.qos.logback.core.Context;
22  import ch.qos.logback.core.CoreConstants;
23  import ch.qos.logback.core.spi.ContextAwareBase;
24  
25  public class ContextUtil extends ContextAwareBase {
26  
27    public ContextUtil(Context context) {
28      setContext(context);
29    }
30  
31    static String getLocalHostName() throws UnknownHostException {
32      InetAddress localhost = InetAddress.getLocalHost();
33      return localhost.getHostName();
34    }
35  
36    /**
37     * Add the local host's name as a property
38     */
39    public void addHostNameAsProperty() {
40      try {
41        String localhostName =  getLocalHostName();
42        context.putProperty(CoreConstants.HOSTNAME_KEY, localhostName);
43      } catch (UnknownHostException e) {
44        addError("Failed to get local hostname", e);
45      } catch (SecurityException e) {
46        addError("Failed to get local hostname", e);
47      }
48    }
49  
50     public void addProperties(Properties props) {
51      if (props == null) {
52        return;
53      }
54      Iterator i = props.keySet().iterator();
55      while (i.hasNext()) {
56        String key = (String) i.next();
57        context.putProperty(key, props.getProperty(key));
58      }
59    }
60  }