Log.java 15.7 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
6
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
Matt Tucker's avatar
Matt Tucker committed
7
 *
8 9 10
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution, or a commercial license
 * agreement with Jive.
Matt Tucker's avatar
Matt Tucker committed
11
 */
12

Matt Tucker's avatar
Matt Tucker committed
13 14
package org.jivesoftware.util;

15 16 17 18
import org.jivesoftware.util.log.Hierarchy;
import org.jivesoftware.util.log.LogTarget;
import org.jivesoftware.util.log.Logger;
import org.jivesoftware.util.log.Priority;
19
import org.jivesoftware.util.log.format.ExtendedPatternFormatter;
20 21 22 23 24 25 26 27 28
import org.jivesoftware.util.log.output.io.StreamTarget;
import org.jivesoftware.util.log.output.io.rotate.RevolvingFileStrategy;
import org.jivesoftware.util.log.output.io.rotate.RotateStrategyBySize;
import org.jivesoftware.util.log.output.io.rotate.RotatingFileTarget;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
29 30
import java.util.ArrayList;
import java.util.List;
31 32 33
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
Matt Tucker's avatar
Matt Tucker committed
34 35 36 37 38 39 40 41

/**
 * Simple wrapper to the incorporated LogKit to log under a single logging name.
 *
 * @author Bruce Ritchie
 */
public class Log {

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    private static final Logger debugLog = Hierarchy.getDefaultHierarchy().getLoggerFor("Jive-DEBUG");
    private static final Logger infoLog = Hierarchy.getDefaultHierarchy().getLoggerFor("Jive-INFO");
    private static final Logger warnLog = Hierarchy.getDefaultHierarchy().getLoggerFor("Jive-WARN");
    private static final Logger errorLog = Hierarchy.getDefaultHierarchy().getLoggerFor("Jive-ERR");

    private static String logNameDebug = null;
    private static String logNameInfo = null;
    private static String logNameWarn = null;
    private static String logNameError = null;
    private static String debugPattern = null;
    private static String infoPattern = null;
    private static String warnPattern = null;
    private static String errorPattern = null;
    private static String logDirectory = null;

    private static long maxDebugSize = 1024;
    private static long maxInfoSize = 1024;
    private static long maxWarnSize = 1024;
    private static long maxErrorSize = 1024;

    private static boolean debugEnabled;
Matt Tucker's avatar
Matt Tucker committed
63 64

    static {
65 66 67 68
        initLog();
    }

    private Log() { }
Matt Tucker's avatar
Matt Tucker committed
69

70 71 72
    /**
     * This method is used to initialize the Log class. For normal operations this method
     * should <b>never</b> be called, rather it's only publically available so that the class
73
     * can be reset by the setup process once the home directory has been specified.
74 75
     */
    public static void initLog() {
Matt Tucker's avatar
Matt Tucker committed
76
        try {
77
            logDirectory = JiveGlobals.getXMLProperty("log.directory");
78
            if (logDirectory == null) {
79
                if (JiveGlobals.getHomeDirectory() != null) {
80 81 82
                    File openfireHome = new File(JiveGlobals.getHomeDirectory());
                    if (openfireHome.exists() && openfireHome.canWrite()) {
                        logDirectory = (new File(openfireHome, "logs")).toString();
83 84 85 86 87 88 89 90
                    }
                }
            }

            if (!logDirectory.endsWith(File.separator)) {
                logDirectory = logDirectory + File.separator;
            }

Matt Tucker's avatar
Matt Tucker committed
91
            // Make sure the logs directory exists. If not, make it:
92
            File logDir = new File(logDirectory);
Matt Tucker's avatar
Matt Tucker committed
93
            if (!logDir.exists()) {
94
                logDir.mkdir();
Matt Tucker's avatar
Matt Tucker committed
95
            }
96

Matt Tucker's avatar
Matt Tucker committed
97 98 99 100
            logNameDebug = logDirectory + "debug.log";
            logNameInfo = logDirectory + "info.log";
            logNameWarn = logDirectory + "warn.log";
            logNameError = logDirectory + "error.log";
101

102 103 104 105
            debugPattern = JiveGlobals.getXMLProperty("log.debug.format");
            infoPattern = JiveGlobals.getXMLProperty("log.info.format");
            warnPattern = JiveGlobals.getXMLProperty("log.warn.format");
            errorPattern = JiveGlobals.getXMLProperty("log.error.format");
106

107
            try { maxDebugSize = Long.parseLong(JiveGlobals.getXMLProperty("log.debug.size")); }
108
            catch (NumberFormatException e) { /* ignore */ }
109
            try { maxInfoSize = Long.parseLong(JiveGlobals.getXMLProperty("log.info.size")); }
110
            catch (NumberFormatException e) { /* ignore */ }
111
            try { maxWarnSize = Long.parseLong(JiveGlobals.getXMLProperty("log.warn.size")); }
112
            catch (NumberFormatException e) { /* ignore */ }
113
            try { maxErrorSize = Long.parseLong(JiveGlobals.getXMLProperty("log.error.size")); }
114 115
            catch (NumberFormatException e) { /* ignore */ }

116
            debugEnabled = "true".equals(JiveGlobals.getXMLProperty("log.debug.enabled"));
117 118
        }
        catch (Exception e) {
119
            // we'll get an exception if home isn't setup yet - we ignore that since
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
            // it's sure to be logged elsewhere :)
        }

        if (debugPattern == null) {
            debugPattern = "%{time:yyyy.MM.dd HH:mm:ss} %{message}\\n%{throwable}";
        }
        if (infoPattern == null) {
            infoPattern = "%{time:yyyy.MM.dd HH:mm:ss} %{message}\\n%{throwable}";
        }
        if (warnPattern == null) {
            warnPattern = "%{time:yyyy.MM.dd HH:mm:ss} %{message}\\n%{throwable}";
        }
        if (errorPattern == null) {
            errorPattern = "%{time:yyyy.MM.dd HH:mm:ss} [%{method}] %{message}\\n%{throwable}";
        }

        createLogger(debugPattern, logNameDebug, maxDebugSize, debugLog, Priority.DEBUG);
        createLogger(infoPattern, logNameInfo, maxInfoSize, infoLog, Priority.INFO);
        createLogger(warnPattern, logNameWarn, maxWarnSize, warnLog, Priority.WARN);
        createLogger(errorPattern, logNameError, maxErrorSize, errorLog, Priority.ERROR);
140 141 142

        // set up the ties into jdk logging
        Handler jdkLogHandler = new JiveLogHandler();
Andrew Wright's avatar
Andrew Wright committed
143
        jdkLogHandler.setLevel(Level.ALL);
144
        java.util.logging.Logger.getLogger("").addHandler(jdkLogHandler);
145 146 147 148 149 150 151 152 153 154 155
    }

    private static void createLogger(String pattern, String logName, long maxLogSize,
            Logger logger, Priority priority)
    {
        // debug log file
        ExtendedPatternFormatter formatter = new ExtendedPatternFormatter(pattern);
        StreamTarget target = null;
        Exception ioe = null;

        try {
156
            // home was not setup correctly
157
            if (logName == null) {
158
                throw new IOException("LogName was null - OpenfireHome not set?");
159 160 161 162 163
            }
            else {
                RevolvingFileStrategy fileStrategy = new RevolvingFileStrategy(logName, 5);
                RotateStrategyBySize rotateStrategy = new RotateStrategyBySize(maxLogSize * 1024);
                target = new RotatingFileTarget(formatter, rotateStrategy, fileStrategy);
Matt Tucker's avatar
Matt Tucker committed
164 165
            }
        }
166 167 168 169 170 171 172 173 174 175 176
        catch (IOException e) {
            ioe = e;
            // can't log to file, log to stderr
            target = new StreamTarget(System.err, formatter);
        }

        logger.setLogTargets(new LogTarget[] { target } );
        logger.setPriority(priority);

        if (ioe != null) {
            logger.debug("Error occurred opening log file: " + ioe.getMessage());
Matt Tucker's avatar
Matt Tucker committed
177 178 179
        }
    }

180 181 182 183 184 185 186 187 188 189 190 191
    public static void setProductName(String productName) {
        debugPattern = productName + " " + debugPattern;
        infoPattern = productName + " " + infoPattern;
        warnPattern = productName + " " + warnPattern;
        errorPattern = productName + " " + errorPattern;

        createLogger(debugPattern, logNameDebug, maxDebugSize, debugLog, Priority.DEBUG);
        createLogger(infoPattern, logNameInfo, maxInfoSize, infoLog, Priority.INFO);
        createLogger(warnPattern, logNameWarn, maxWarnSize, warnLog, Priority.WARN);
        createLogger(errorPattern, logNameError, maxErrorSize, errorLog, Priority.ERROR);
    }

Matt Tucker's avatar
Matt Tucker committed
192 193 194 195
    public static boolean isErrorEnabled() {
        return errorLog.isErrorEnabled();
    }

196 197 198 199 200 201 202 203 204
    public static boolean isFatalEnabled() {
        return errorLog.isFatalErrorEnabled();
    }

    public static boolean isDebugEnabled() {
        return debugEnabled;
    }

    public static void setDebugEnabled(boolean enabled) {
205
        JiveGlobals.setXMLProperty("log.debug.enabled", Boolean.toString(enabled));
206 207 208
        debugEnabled = enabled;
    }

Matt Tucker's avatar
Matt Tucker committed
209 210 211 212 213 214 215 216
    public static boolean isInfoEnabled() {
        return infoLog.isInfoEnabled();
    }

    public static boolean isWarnEnabled() {
        return warnLog.isWarnEnabled();
    }

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    public static void debug(String s) {
        if (isDebugEnabled()) {
            debugLog.debug(s);
        }
    }

    public static void debug(Throwable throwable) {
        if (isDebugEnabled()) {
            debugLog.debug("", throwable);
        }
    }

    public static void debug(String s, Throwable throwable) {
        if (isDebugEnabled()) {
            debugLog.debug(s, throwable);
        }
    }

235
    public static void markDebugLogFile(String username) {
236
        RotatingFileTarget target = (RotatingFileTarget) debugLog.getLogTargets()[0];
237
        markLogFile(username, target);
238 239 240 241 242 243 244 245 246 247 248 249 250
    }

    public static void rotateDebugLogFile() {
        RotatingFileTarget target = (RotatingFileTarget) debugLog.getLogTargets()[0];
        try {
            target.rotate();
        }
        catch (IOException e) {
            System.err.println("Warning: There was an error rotating the Jive debug log file. " +
                    "Logging may not work correctly until a restart happens.");
        }
    }

Matt Tucker's avatar
Matt Tucker committed
251
    public static void info(String s) {
252 253 254
        if (isInfoEnabled()) {
            infoLog.info(s);
        }
Matt Tucker's avatar
Matt Tucker committed
255 256 257
    }

    public static void info(Throwable throwable) {
258 259 260
        if (isInfoEnabled()) {
            infoLog.info("", throwable);
        }
Matt Tucker's avatar
Matt Tucker committed
261 262 263
    }

    public static void info(String s, Throwable throwable) {
264 265 266 267 268
        if (isInfoEnabled()) {
            infoLog.info(s, throwable);
        }
    }

269
    public static void markInfoLogFile(String username) {
270
        RotatingFileTarget target = (RotatingFileTarget) infoLog.getLogTargets()[0];
271
        markLogFile(username, target);
272 273 274 275 276 277 278 279 280 281 282
    }

    public static void rotateInfoLogFile() {
        RotatingFileTarget target = (RotatingFileTarget) infoLog.getLogTargets()[0];
        try {
            target.rotate();
        }
        catch (IOException e) {
            System.err.println("Warning: There was an error rotating the Jive info log file. " +
                    "Logging may not work correctly until a restart happens.");
        }
Matt Tucker's avatar
Matt Tucker committed
283 284 285
    }

    public static void warn(String s) {
286 287 288
        if (isWarnEnabled()) {
            warnLog.warn(s);
        }
Matt Tucker's avatar
Matt Tucker committed
289 290 291
    }

    public static void warn(Throwable throwable) {
292 293 294
        if (isWarnEnabled()) {
            warnLog.warn("", throwable);
        }
Matt Tucker's avatar
Matt Tucker committed
295 296 297
    }

    public static void warn(String s, Throwable throwable) {
298 299 300 301 302
        if (isWarnEnabled()) {
            warnLog.warn(s, throwable);
        }
    }

303
    public static void markWarnLogFile(String username) {
304
        RotatingFileTarget target = (RotatingFileTarget) warnLog.getLogTargets()[0];
305
        markLogFile(username, target);
306 307 308 309 310 311 312 313 314 315 316
    }

    public static void rotateWarnLogFile() {
        RotatingFileTarget target = (RotatingFileTarget) warnLog.getLogTargets()[0];
        try {
            target.rotate();
        }
        catch (IOException e) {
            System.err.println("Warning: There was an error rotating the Jive warn log file. " +
                    "Logging may not work correctly until a restart happens.");
        }
Matt Tucker's avatar
Matt Tucker committed
317 318 319
    }

    public static void error(String s) {
320 321 322 323 324 325
        if (isErrorEnabled()) {
            errorLog.error(s);
            if (isDebugEnabled()) {
                printToStdErr(s, null);
            }
        }
Matt Tucker's avatar
Matt Tucker committed
326 327 328
    }

    public static void error(Throwable throwable) {
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
        if (isErrorEnabled()) {
            errorLog.error("", throwable);
            if (isDebugEnabled()) {
                printToStdErr(null, throwable);
            }
        }
    }

    public static void error(String s, Throwable throwable) {
        if (isErrorEnabled()) {
            errorLog.error(s, throwable);
            if (isDebugEnabled()) {
                printToStdErr(s, throwable);
            }
        }
    }

346
    public static void markErrorLogFile(String username) {
347
        RotatingFileTarget target = (RotatingFileTarget) errorLog.getLogTargets()[0];
348
        markLogFile(username, target);
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    }

    public static void rotateErrorLogFile() {
        RotatingFileTarget target = (RotatingFileTarget) errorLog.getLogTargets()[0];
        try {
            target.rotate();
        }
        catch (IOException e) {
            System.err.println("Warning: There was an error rotating the Jive error log file. " +
                    "Logging may not work correctly until a restart happens.");
        }
    }

    public static void fatal(String s) {
        if (isFatalEnabled()) {
            errorLog.fatalError(s);
            if (isDebugEnabled()) {
                printToStdErr(s, null);
            }
        }
    }

    public static void fatal(Throwable throwable) {
        if (isFatalEnabled()) {
            errorLog.fatalError("", throwable);
            if (isDebugEnabled()) {
                printToStdErr(null, throwable);
            }
        }
    }

    public static void fatal(String s, Throwable throwable) {
        if (isFatalEnabled()) {
            errorLog.fatalError(s, throwable);
            if (isDebugEnabled()) {
                printToStdErr(s, throwable);
            }
        }
Matt Tucker's avatar
Matt Tucker committed
387 388 389
    }

    /**
390 391
     * Returns the directory that log files exist in. The directory name will
     * have a File.separator as the last character in the string.
Matt Tucker's avatar
Matt Tucker committed
392
     *
393
     * @return the directory that log files exist in.
Matt Tucker's avatar
Matt Tucker committed
394
     */
395 396 397 398
    public static String getLogDirectory() {
        return logDirectory;
    }

399
    private static void markLogFile(String username, RotatingFileTarget target) {
400
        List args = new ArrayList();
401
        args.add(username);
402 403 404 405
        args.add(JiveGlobals.formatDateTime(new java.util.Date()));
        target.write(LocaleUtils.getLocalizedString("log.marker_inserted_by", args) + "\n");
    }

406 407 408 409 410 411 412 413 414 415 416
    private static void printToStdErr(String s, Throwable throwable) {
        if (s != null) {
            System.err.println(s);
        }
        if (throwable != null) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            throwable.printStackTrace(pw);
            System.err.print(sw.toString());
            System.err.print("\n");
        }
Matt Tucker's avatar
Matt Tucker committed
417
    }
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479

    private static final class JiveLogHandler extends Handler {

        public void publish(LogRecord record) {

            Level level = record.getLevel();
            Throwable throwable = record.getThrown();


            if (Level.SEVERE.equals(level)) {

                if (throwable != null) {
                    Log.error(record.getMessage(), throwable);
                }
                else {
                    Log.error(record.getMessage());
                }

            }
            else if (Level.WARNING.equals(level)) {

                if (throwable != null) {
                    Log.warn(record.getMessage(), throwable);
                }
                else {
                    Log.warn(record.getMessage());
                }


            }
            else if (Level.INFO.equals(level)) {

                if (throwable != null) {
                    Log.info(record.getMessage(), throwable);
                }
                else {
                    Log.info(record.getMessage());
                }

            }
            else {
                // else FINE,FINER,FINEST

                if (throwable != null) {
                    Log.debug(record.getMessage(), throwable);
                }
                else {
                    Log.debug(record.getMessage());
                }

            }
        }

        public void flush() {
            // do nothing
        }

        public void close() throws SecurityException {
            // do nothing
        }
    }

480
}