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