001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.test.log;
016    
017    import com.liferay.portal.kernel.log.Log;
018    import com.liferay.portal.kernel.log.LogFactoryUtil;
019    import com.liferay.portal.kernel.log.LogWrapper;
020    import com.liferay.portal.log.Log4jLogImpl;
021    
022    import org.apache.log4j.Level;
023    import org.apache.log4j.Logger;
024    
025    /**
026     * @author Shuyang Zhou
027     */
028    public class Log4JLoggerTestUtil {
029    
030            public static CaptureAppender configureLog4JLogger(
031                    String name, Level level) {
032    
033                    LogWrapper logWrapper = (LogWrapper)LogFactoryUtil.getLog(name);
034    
035                    Log log = logWrapper.getWrappedLog();
036    
037                    if (!(log instanceof Log4jLogImpl)) {
038                            throw new IllegalStateException(
039                                    "Log " + name + " is not a Log4j logger");
040                    }
041    
042                    Log4jLogImpl log4jLogImpl = (Log4jLogImpl)log;
043    
044                    Logger logger = log4jLogImpl.getWrappedLogger();
045    
046                    CaptureAppender captureAppender = new CaptureAppender(logger);
047    
048                    logger.addAppender(captureAppender);
049    
050                    logger.setLevel(level);
051    
052                    return captureAppender;
053            }
054    
055            public static Level setLoggerLevel(String name, Level level) {
056                    LogWrapper logWrapper = (LogWrapper)LogFactoryUtil.getLog(name);
057    
058                    Log log = logWrapper.getWrappedLog();
059    
060                    if (!(log instanceof Log4jLogImpl)) {
061                            throw new IllegalStateException(
062                                    "Log " + name + " is not a Log4j logger");
063                    }
064    
065                    Log4jLogImpl log4jLogImpl = (Log4jLogImpl)log;
066    
067                    Logger logger = log4jLogImpl.getWrappedLogger();
068    
069                    Level oldLevel = logger.getLevel();
070    
071                    logger.setLevel(level);
072    
073                    return oldLevel;
074            }
075    
076    }