Logger.java 18.4 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the LICENSE file.
 */
package org.jivesoftware.util.log;

/**
 * The object interacted with by client objects to perform logging.
 *
 * @author <a href="mailto:peter@apache.org">Peter Donald</a>
 */
public class Logger {
    ///Separator character use to separate different categories
    public final static char CATEGORY_SEPARATOR = '.';

    ///The ErrorHandler associated with Logger
    private final ErrorHandler m_errorHandler;

    ///Logger to inherit logtargets and priorities from
    private final Logger m_parent;

    ///the fully qualified name of category
    private final String m_category;

    ///The list of child loggers associated with this logger
    private Logger[] m_children;

    ///The log-targets this logger writes to
    private LogTarget[] m_logTargets;

    ///Indicate that logTargets were set with setLogTargets() rather than inherited
    private boolean m_logTargetsForceSet;

    ///The priority threshold associated with logger
    private Priority m_priority;

    ///Indicate that priority was set with setPriority() rather than inherited
    private boolean m_priorityForceSet;

    /**
     * True means LogEvents will be sent to parents LogTargets
     * aswell as the ones set for this Logger.
     */
    private boolean m_additivity;

    /**
     * Protected constructor for use inside the logging toolkit.
     * You should not be using this constructor directly.
     *
     * @param errorHandler the ErrorHandler logger uses to log errors
     * @param category     the fully qualified name of category
     * @param logTargets   the LogTargets associated with logger
     * @param parent       the parent logger (used for inheriting from)
     */
    Logger(final ErrorHandler errorHandler,
           final String category,
           final LogTarget[] logTargets,
           final Logger parent) {
        m_errorHandler = errorHandler;
        m_category = category;
        m_logTargets = logTargets;
        m_parent = parent;

        if (null == m_logTargets) {
            unsetLogTargets();
        }

        unsetPriority();
    }

    /**
     * Determine if messages of priority DEBUG will be logged.
     *
     * @return true if DEBUG messages will be logged
     */
    public final boolean isDebugEnabled() {
        return m_priority.isLowerOrEqual(Priority.DEBUG);
    }

    /**
     * Log a debug priority event.
     *
     * @param message   the message
     * @param throwable the throwable
     */
    public final void debug(final String message, final Throwable throwable) {
        if (isDebugEnabled()) {
            output(Priority.DEBUG, message, throwable);
        }
    }

    /**
     * Log a debug priority event.
     *
     * @param message the message
     */
    public final void debug(final String message) {
        if (isDebugEnabled()) {
            output(Priority.DEBUG, message, null);
        }
    }

    /**
     * Determine if messages of priority INFO will be logged.
     *
     * @return true if INFO messages will be logged
     */
    public final boolean isInfoEnabled() {
        return m_priority.isLowerOrEqual(Priority.INFO);
    }

    /**
     * Log a info priority event.
     *
     * @param message the message
     */
    public final void info(final String message, final Throwable throwable) {
        if (isInfoEnabled()) {
            output(Priority.INFO, message, throwable);
        }
    }

    /**
     * Log a info priority event.
     *
     * @param message the message
     */
    public final void info(final String message) {
        if (isInfoEnabled()) {
            output(Priority.INFO, message, null);
        }
    }

    /**
     * Determine if messages of priority WARN will be logged.
     *
     * @return true if WARN messages will be logged
     */
    public final boolean isWarnEnabled() {
        return m_priority.isLowerOrEqual(Priority.WARN);
    }

    /**
     * Log a warn priority event.
     *
     * @param message   the message
     * @param throwable the throwable
     */
    public final void warn(final String message, final Throwable throwable) {
        if (isWarnEnabled()) {
            output(Priority.WARN, message, throwable);
        }
    }

    /**
     * Log a warn priority event.
     *
     * @param message the message
     */
    public final void warn(final String message) {
        if (isWarnEnabled()) {
            output(Priority.WARN, message, null);
        }
    }

    /**
     * Determine if messages of priority ERROR will be logged.
     *
     * @return true if ERROR messages will be logged
     */
    public final boolean isErrorEnabled() {
        return m_priority.isLowerOrEqual(Priority.ERROR);
    }

    /**
     * Log a error priority event.
     *
     * @param message   the message
     * @param throwable the throwable
     */
    public final void error(final String message, final Throwable throwable) {
        if (isErrorEnabled()) {
            output(Priority.ERROR, message, throwable);
        }
    }

    /**
     * Log a error priority event.
     *
     * @param message the message
     */
    public final void error(final String message) {
        if (isErrorEnabled()) {
            output(Priority.ERROR, message, null);
        }
    }

    /**
     * Determine if messages of priority FATAL_ERROR will be logged.
     *
     * @return true if FATAL_ERROR messages will be logged
     */
    public final boolean isFatalErrorEnabled() {
        return m_priority.isLowerOrEqual(Priority.FATAL_ERROR);
    }

    /**
     * Log a fatalError priority event.
     *
     * @param message   the message
     * @param throwable the throwable
     */
    public final void fatalError(final String message, final Throwable throwable) {
        if (isFatalErrorEnabled()) {
            output(Priority.FATAL_ERROR, message, throwable);
        }
    }

    /**
     * Log a fatalError priority event.
     *
     * @param message the message
     */
    public final void fatalError(final String message) {
        if (isFatalErrorEnabled()) {
            output(Priority.FATAL_ERROR, message, null);
        }
    }

    /**
     * Make this logger additive, which means send all log events to parent
     * loggers LogTargets regardless of whether or not the
     * LogTargets have been overidden.
     * <p/>
     * This is derived from Log4js notion of Additivity.
     *
     * @param additivity true to make logger additive, false otherwise
     */
    public final void setAdditivity(final boolean additivity) {
        m_additivity = additivity;
    }

    /**
Matt Tucker's avatar
Matt Tucker committed
247
     * Determine if messages of priority will be logged.
Matt Tucker's avatar
Matt Tucker committed
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 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 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 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
     *
     * @return true if messages will be logged
     */
    public final boolean isPriorityEnabled(final Priority priority) {
        return m_priority.isLowerOrEqual(priority);
    }

    /**
     * Log a event at specific priority with a certain message and throwable.
     *
     * @param message   the message
     * @param priority  the priority
     * @param throwable the throwable
     */
    public final void log(final Priority priority,
                          final String message,
                          final Throwable throwable) {
        if (m_priority.isLowerOrEqual(priority)) {
            output(priority, message, throwable);
        }
    }

    /**
     * Log a event at specific priority with a certain message.
     *
     * @param message  the message
     * @param priority the priority
     */
    public final void log(final Priority priority, final String message) {
        log(priority, message, null);
    }

    /**
     * Set the priority for this logger.
     *
     * @param priority the priority
     */
    public synchronized void setPriority(final Priority priority) {
        m_priority = priority;
        m_priorityForceSet = true;
        resetChildPriorities(false);
    }

    /**
     * Unset the priority of Logger.
     * (Thus it will use it's parent's priority or DEBUG if no parent.
     */
    public synchronized void unsetPriority() {
        unsetPriority(false);
    }

    /**
     * Unset the priority of Logger.
     * (Thus it will use it's parent's priority or DEBUG if no parent.
     * If recursive is true unset priorities of all child loggers.
     *
     * @param recursive true to unset priority of all child loggers
     */
    public synchronized void unsetPriority(final boolean recursive) {
        if (null != m_parent)
            m_priority = m_parent.m_priority;
        else
            m_priority = Priority.DEBUG;

        m_priorityForceSet = false;
        resetChildPriorities(recursive);
    }

    /**
     * Set the log targets for this logger.
     *
     * @param logTargets the Log Targets
     */
    public synchronized void setLogTargets(final LogTarget[] logTargets) {
        m_logTargets = logTargets;
        setupErrorHandlers();
        m_logTargetsForceSet = true;
        resetChildLogTargets(false);
    }

    /**
     * Unset the logtargets for this logger.
     * This logger (and thus all child loggers who don't specify logtargets) will
     * inherit from the parents LogTargets.
     */
    public synchronized void unsetLogTargets() {
        unsetLogTargets(false);
    }

    /**
     * Unset the logtargets for this logger and all child loggers if recursive is set.
     * The loggers unset (and all child loggers who don't specify logtargets) will
     * inherit from the parents LogTargets.
     */
    public synchronized void unsetLogTargets(final boolean recursive) {
        if (null != m_parent)
            m_logTargets = m_parent.safeGetLogTargets();
        else
            m_logTargets = null;

        m_logTargetsForceSet = false;
        resetChildLogTargets(recursive);
    }

    /**
     * Get all the child Loggers of current logger.
     *
     * @return the child loggers
     */
    public synchronized Logger[] getChildren() {
        if (null == m_children) return new Logger[0];

        final Logger[] children = new Logger[m_children.length];

        for (int i = 0; i < children.length; i++) {
            children[i] = m_children[i];
        }

        return children;
    }

    /**
     * Create a new child logger.
     * The category of child logger is [current-category].subcategory
     *
     * @param subCategory the subcategory of this logger
     * @return the new logger
     * @throws IllegalArgumentException if subCategory has an empty element name
     */
    public synchronized Logger getChildLogger(final String subCategory)
            throws IllegalArgumentException {
        final int end = subCategory.indexOf(CATEGORY_SEPARATOR);

        String nextCategory = null;
        String remainder = null;

        if (-1 == end)
            nextCategory = subCategory;
        else {
            if (end == 0) {
                throw new IllegalArgumentException("Logger categories MUST not have empty elements");
            }

            nextCategory = subCategory.substring(0, end);
            remainder = subCategory.substring(end + 1);
        }

        //Get FQN for category
        String category = null;
        if (m_category.equals(""))
            category = nextCategory;
        else {
            category = m_category + CATEGORY_SEPARATOR + nextCategory;
        }

        //Check existing children to see if they
        //contain next Logger for step in category
        if (null != m_children) {
            for (int i = 0; i < m_children.length; i++) {
                if (m_children[i].m_category.equals(category)) {
                    if (null == remainder)
                        return m_children[i];
                    else
                        return m_children[i].getChildLogger(remainder);
                }
            }
        }

        //Create new logger
        final Logger child = new Logger(m_errorHandler, category, null, this);

        //Add new logger to child list
        if (null == m_children) {
            m_children = new Logger[]{child};
        }
        else {
            final Logger[] children = new Logger[m_children.length + 1];
            System.arraycopy(m_children, 0, children, 0, m_children.length);
            children[m_children.length] = child;
            m_children = children;
        }

        if (null == remainder)
            return child;
        else
            return child.getChildLogger(remainder);
    }

    /**
     * Retrieve priority associated with Logger.
     *
     * @return the loggers priority
     * @deprecated This method violates Inversion of Control principle.
     *             It will downgraded to protected access in a future
     *             release. When user needs to check priority it is advised
     *             that they use the is[Priority]Enabled() functions.
     */
    public final Priority getPriority() {
        return m_priority;
    }

    /**
     * Retrieve category associated with logger.
     *
     * @return the Category
     * @deprecated This method violates Inversion of Control principle.
     *             If you are relying on its presence then there may be
     *             something wrong with the design of your system
     */
    public final String getCategory() {
        return m_category;
    }

    /**
     * Get a copy of log targets for this logger.
     *
     * @return the child loggers
     */
    public LogTarget[] getLogTargets() {
467 468 469
        // Jive change - we ignore the deprecated warning above and just return the log targets
        // since it's a closed system for us anyways
        return m_logTargets;
Matt Tucker's avatar
Matt Tucker committed
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
    }

    /**
     * Internal method to do actual outputting.
     *
     * @param priority  the priority
     * @param message   the message
     * @param throwable the throwable
     */
    private final void output(final Priority priority,
                              final String message,
                              final Throwable throwable) {
        final LogEvent event = new LogEvent();
        event.setCategory(m_category);
//        event.setContextStack( ContextStack.getCurrentContext( false ) );
        event.setContextMap(ContextMap.getCurrentContext(false));

        if (null != message) {
            event.setMessage(message);
        }
        else {
            event.setMessage("");
        }

        event.setThrowable(throwable);
        event.setPriority(priority);

        //this next line can kill performance. It may be wise to
        //disable it sometimes and use a more granular approach
        event.setTime(System.currentTimeMillis());

        output(event);
    }

    private final void output(final LogEvent event) {
        //cache a copy of targets for thread safety
        //It is now possible for another thread
        //to replace m_logTargets
        final LogTarget[] targets = m_logTargets;

        if (null == targets) {
            final String message = "LogTarget is null for category '" + m_category + "'";
            m_errorHandler.error(message, null, event);
        }
        else if (!m_additivity) {
            fireEvent(event, targets);
        }
        else {
            //If log targets were not inherited, additivity is true
            //then fire an event to local targets
            if (m_logTargetsForceSet) {
                fireEvent(event, targets);
            }

            //if we have a parent Logger then send log event to parent
            if (null != m_parent) {
                m_parent.output(event);
            }
        }
    }

    private final void fireEvent(final LogEvent event, final LogTarget[] targets) {
        for (int i = 0; i < targets.length; i++) {
            //No need to clone array as addition of a log-target
            //will result in changin whole array
            targets[i].processEvent(event);
        }
    }

    /**
     * Update priority of children if any.
     */
    private synchronized void resetChildPriorities(final boolean recursive) {
        if (null == m_children) return;

        final Logger[] children = m_children;

        for (int i = 0; i < children.length; i++) {
            children[i].resetPriority(recursive);
        }
    }

    /**
     * Update priority of this Logger.
     * If this loggers priority was manually set then ignore
     * otherwise get parents priority and update all children's priority.
     */
    private synchronized void resetPriority(final boolean recursive) {
        if (recursive) {
            m_priorityForceSet = false;
        }
        else if (m_priorityForceSet) {
            return;
        }

        m_priority = m_parent.m_priority;
        resetChildPriorities(recursive);
    }

    /**
     * Retrieve logtarget array contained in logger.
     * This method is provided so that child Loggers can access a
     * copy of  parents LogTargets.
     *
     * @return the array of LogTargets
     */
    private synchronized LogTarget[] safeGetLogTargets() {
        if (null == m_logTargets) {
            if (null == m_parent)
                return new LogTarget[0];
            else
                return m_parent.safeGetLogTargets();
        }
        else {
            final LogTarget[] logTargets = new LogTarget[m_logTargets.length];

            for (int i = 0; i < logTargets.length; i++) {
                logTargets[i] = m_logTargets[i];
            }

            return logTargets;
        }
    }

    /**
     * Update logTargets of children if any.
     */
    private synchronized void resetChildLogTargets(final boolean recursive) {
        if (null == m_children) return;

        for (int i = 0; i < m_children.length; i++) {
            m_children[i].resetLogTargets(recursive);
        }
    }

    /**
     * Set ErrorHandlers of LogTargets if necessary.
     */
    private synchronized void setupErrorHandlers() {
        if (null == m_logTargets) return;

        for (int i = 0; i < m_logTargets.length; i++) {
            final LogTarget target = m_logTargets[i];
            if (target instanceof ErrorAware) {
                ((ErrorAware)target).setErrorHandler(m_errorHandler);
            }
        }
    }

    /**
     * Update logTarget of this Logger.
     * If this loggers logTarget was manually set then ignore
     * otherwise get parents logTarget and update all children's logTarget.
     */
    private synchronized void resetLogTargets(final boolean recursive) {
        if (recursive) {
            m_logTargetsForceSet = false;
        }
        else if (m_logTargetsForceSet) {
            return;
        }

        m_logTargets = m_parent.safeGetLogTargets();
        resetChildLogTargets(recursive);
    }
}