1 /*
   2  * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.nashorn.internal.runtime;
  27 
  28 import java.util.HashMap;

  29 import java.util.Map;
  30 import java.util.Map.Entry;
  31 import java.util.logging.ConsoleHandler;
  32 import java.util.logging.Formatter;
  33 import java.util.logging.Handler;
  34 import java.util.logging.Level;
  35 import java.util.logging.LogRecord;
  36 import java.util.logging.Logger;
  37 
  38 /**
  39  * Logging system for getting loggers for arbitrary subsystems as
  40  * specified on the command line. Supports all standard log levels
  41  *
  42  */
  43 public final class Logging {
  44 
  45     private Logging() {
  46     }
  47 
  48     /** Loggers */
  49 
  50     private static final Logger disabledLogger = Logger.getLogger("disabled");
  51 
  52     static {
  53         try {
  54             Logging.disabledLogger.setLevel(Level.OFF);
  55         } catch (final SecurityException e) {
  56             //ignored
  57         }
  58     }
  59 
  60     /** Maps logger name to loggers. Names are typically per package */
  61     private static final Map<String, Logger> loggers = new HashMap<>();
  62 
  63     private static String lastPart(final String packageName) {
  64         final String[] parts = packageName.split("\\.");
  65         if (parts.length == 0) {
  66             return packageName;
  67         }
  68         return parts[parts.length - 1];
  69     }
  70 
  71     /**
  72      * Get a logger for a given class, generating a logger name based on the
  73      * class name
  74      *
  75      * @param name the name to use as key for the logger
  76      * @return the logger
  77      */
  78     public static Logger getLogger(final String name) {
  79         final Logger logger = Logging.loggers.get(name);
  80         if (logger != null) {
  81             return logger;
  82         }
  83         return Logging.disabledLogger;
  84     }
  85 
  86     /**
  87      * Get a logger for a given name or create it if not already there, typically
  88      * used for mapping system properties to loggers
  89      *
  90      * @param name the name to use as key
  91      * @param level log lever to reset existing logger with, or create new logger with
  92      * @return the logger
  93      */
  94     public static Logger getOrCreateLogger(final String name, final Level level) {
  95         final Logger logger = Logging.loggers.get(name);
  96         if (logger == null) {
  97             return instantiateLogger(name, level);
  98         }
  99         logger.setLevel(level);
 100         return logger;
 101     }
 102 
 103     /**
 104      * Initialization function that is called to instantiate the logging system. It takes
 105      * logger names (keys) and logging labels respectively
 106      *
 107      * @param map a map where the key is a logger name and the value a logging level
 108      * @throws IllegalArgumentException if level or names cannot be parsed
 109      */
 110     public static void initialize(final Map<String, String> map) throws IllegalArgumentException {
 111         try {
 112             for (final Entry<String, String> entry : map.entrySet()) {
 113                 Level level;
 114 
 115                 final String key   = entry.getKey();
 116                 final String value = entry.getValue();
 117                 if ("".equals(value)) {
 118                     level = Level.INFO;
 119                 } else {
 120                     level = Level.parse(value.toUpperCase());
 121                 }
 122 
 123                 final String name = Logging.lastPart(key);
 124                 final Logger logger = instantiateLogger(name, level);
 125 
 126                 Logging.loggers.put(name, logger);
 127             }
 128         } catch (final IllegalArgumentException | SecurityException e) {
 129             throw e;
 130         }
 131     }
 132 
 133     private static Logger instantiateLogger(final String name, final Level level) {
 134         final Logger logger = java.util.logging.Logger.getLogger(name);
 135         for (final Handler h : logger.getHandlers()) {
 136             logger.removeHandler(h);
 137         }
 138 
 139         logger.setLevel(level);
 140         logger.setUseParentHandlers(false);
 141         final Handler c = new ConsoleHandler();
 142 
 143         c.setFormatter(new Formatter() {
 144             @Override
 145             public String format(final LogRecord record) {
 146                 final StringBuilder sb = new StringBuilder();
 147 
 148                 sb.append('[')
 149                    .append(record.getLoggerName())
 150                    .append("] ")
 151                    .append(record.getMessage())
 152                    .append('\n');
 153 
 154                 return sb.toString();
 155             }
 156         });
 157         logger.addHandler(c);
 158         c.setLevel(level);
 159 
 160         return logger;
 161     }
 162 
 163 }
--- EOF ---