zoukankan      html  css  js  c++  java
  • [Log4J]一个只打Console并且设有最高级别的Appender

    /*
     * Copyright 1999-2005 The Apache Software Foundation.
     * 
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     * 
     *      http://www.apache.org/licenses/LICENSE-2.0
     * 
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    
    
    import java.io.IOException;
    import java.io.OutputStream;
    
    import org.apache.log4j.Layout;
    import org.apache.log4j.Level;
    import org.apache.log4j.WriterAppender;
    import org.apache.log4j.helpers.LogLog;
    import org.apache.log4j.spi.LoggingEvent;
    
    /**
     * ConsoleAppender appends log events to <code>System.out</code> or
     * <code>System.err</code> using a layout specified by the user. The default
     * target is <code>System.out</code>.
     * 
     * @author Ceki Gülcü
     * @author Curt Arnold
     * @since 1.1
     */
    public class MyAppender extends WriterAppender {
    
    	public static final String SYSTEM_OUT = "System.out";
    	public static final String SYSTEM_ERR = "System.err";
    
    	protected String target = SYSTEM_OUT;
    
    	/**
    	 * Determines if the appender honors reassignments of System.out or
    	 * System.err made after configuration.
    	 */
    	private boolean follow = false;
    
    	/**
    	 * Constructs an unconfigured appender.
    	 */
    	public MyAppender() {
    	}
    
    	/**
    	 * Creates a configured appender.
    	 * 
    	 * @param layout
    	 *            layout, may not be null.
    	 */
    	public MyAppender(Layout layout) {
    		this(layout, SYSTEM_OUT);
    	}
    
    	/**
    	 * Creates a configured appender.
    	 * 
    	 * @param layout
    	 *            layout, may not be null.
    	 * @param targetStr
    	 *            target, either "System.err" or "System.out".
    	 */
    	public MyAppender(Layout layout, String target) {
    		setLayout(layout);
    		setTarget(target);
    		activateOptions();
    	}
    
    	/**
    	 * Sets the value of the <b>Target</b> option. Recognized values are
    	 * "System.out" and "System.err". Any other value will be ignored.
    	 * */
    	public void setTarget(String value) {
    		String v = value.trim();
    
    		if (SYSTEM_OUT.equalsIgnoreCase(v)) {
    			target = SYSTEM_OUT;
    		} else if (SYSTEM_ERR.equalsIgnoreCase(v)) {
    			target = SYSTEM_ERR;
    		} else {
    			targetWarn(value);
    		}
    	}
    
    	/**
    	 * Returns the current value of the <b>Target</b> property. The default
    	 * value of the option is "System.out".
    	 * 
    	 * See also {@link #setTarget}.
    	 * */
    	public String getTarget() {
    		return target;
    	}
    
    	/**
    	 * Sets whether the appender honors reassignments of System.out or
    	 * System.err made after configuration.
    	 * 
    	 * @param newValue
    	 *            if true, appender will use value of System.out or System.err
    	 *            in force at the time when logging events are appended.
    	 * @since 1.2.13
    	 */
    	public final void setFollow(final boolean newValue) {
    		follow = newValue;
    	}
    
    	/**
    	 * Gets whether the appender honors reassignments of System.out or
    	 * System.err made after configuration.
    	 * 
    	 * @return true if appender will use value of System.out or System.err in
    	 *         force at the time when logging events are appended.
    	 * @since 1.2.13
    	 */
    	public final boolean getFollow() {
    		return follow;
    	}
    
    	@Override
    	public void append(LoggingEvent event) {
    
    		// Reminder: the nesting of calls is:
    		//
    		// doAppend()
    		// - check threshold
    		// - filter
    		// - append();
    		// - checkEntryConditions();
    		// - subAppend();
    		//[yangyh]
    		if (event.getLevel().isGreaterOrEqual(Level.WARN)) {
    			return;
    		}
    		if (!checkEntryConditions()) {
    			return;
    		}
    		subAppend(event);
    	}
    
    	void targetWarn(String val) {
    		LogLog.warn("[" + val + "] should be System.out or System.err.");
    		LogLog.warn("Using previously set target, System.out by default.");
    	}
    
    	/**
    	 * Prepares the appender for use.
    	 */
    	@Override
    	public void activateOptions() {
    		if (follow) {
    			if (target.equals(SYSTEM_ERR)) {
    				setWriter(createWriter(new SystemErrStream()));
    			} else {
    				setWriter(createWriter(new SystemOutStream()));
    			}
    		} else {
    			if (target.equals(SYSTEM_ERR)) {
    				setWriter(createWriter(System.err));
    			} else {
    				setWriter(createWriter(System.out));
    			}
    		}
    		super.activateOptions();
    	}
    
    	/**
    	 * {@inheritDoc}
    	 */
    	@Override
    	protected final void closeWriter() {
    		if (follow) {
    			super.closeWriter();
    		}
    	}
    
    	/**
    	 * An implementation of OutputStream that redirects to the current
    	 * System.err.
    	 * 
    	 */
    	private static class SystemErrStream extends OutputStream {
    		public SystemErrStream() {
    		}
    
    		@Override
    		public void close() {
    		}
    
    		@Override
    		public void flush() {
    			System.err.flush();
    		}
    
    		@Override
    		public void write(final byte[] b) throws IOException {
    			System.err.write(b);
    		}
    
    		@Override
    		public void write(final byte[] b, final int off, final int len) throws IOException {
    			System.err.write(b, off, len);
    		}
    
    		@Override
    		public void write(final int b) throws IOException {
    			System.err.write(b);
    		}
    	}
    
    	/**
    	 * An implementation of OutputStream that redirects to the current
    	 * System.out.
    	 * 
    	 */
    	private static class SystemOutStream extends OutputStream {
    		public SystemOutStream() {
    		}
    
    		@Override
    		public void close() {
    		}
    
    		@Override
    		public void flush() {
    			System.out.flush();
    		}
    
    		@Override
    		public void write(final byte[] b) throws IOException {
    			System.out.write(b);
    		}
    
    		@Override
    		public void write(final byte[] b, final int off, final int len) throws IOException {
    			System.out.write(b, off, len);
    		}
    
    		@Override
    		public void write(final int b) throws IOException {
    			System.out.write(b);
    		}
    	}
    
    }
    

      log4j.properties:

    ### set log levels ###
    log4j.rootLogger = debug , stderr, D, A1

    log4j.appender.stdout = org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target = System.out
    log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{1}:%L - %m%n

    log4j.appender.stderr = org.apache.log4j.ConsoleAppender
    log4j.appender.stderr.Target = System.err
    log4j.appender.stderr.Threshold = WARN
    log4j.appender.stderr.layout = org.apache.log4j.PatternLayout
    log4j.appender.stderr.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{1}:%L - %m%n


    log4j.appender.A1 = com.baidu.tv.video.fetcher.log.MyAppender
    log4j.appender.A1.Target = System.out
    log4j.appender.A1.Threshold = DEBUG
    log4j.appender.A1.layout = org.apache.log4j.PatternLayout
    log4j.appender.A1.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{1}:%L - %m%n

    log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
    log4j.appender.D.File = logs/error.log
    log4j.appender.D.Append = true
    log4j.appender.D.Threshold = WARN
    log4j.appender.D.layout = org.apache.log4j.PatternLayout
    log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n

    貌似现在的Appender只有最低级别:Threshold
    这里重写了WriterAppander的append方法

    躲猫猫社团团长 http://t.sina.com.cn/coolria

  • 相关阅读:
    记忆碎片:我的2007
    查看 Oracle 是用spfile 启动还是 pfile 启动
    Oracle 10g OCP 042 题库 71120 题 共168题
    Oracle OLAP 与 OLTP 介绍
    Oracle Data Guard Switchover 切换
    Linux 终端访问 FTP 及 上传下载 文件
    多表连接的三种方式详解 HASH JOIN MERGE JOIN NESTED LOOP
    Oracle 表连接方式(内连接/外连接/自连接) 详解
    Oracle 表连接方式(内连接/外连接/自连接) 详解
    查看 Oracle 是用spfile 启动还是 pfile 启动
  • 原文地址:https://www.cnblogs.com/yangyh/p/3098390.html
Copyright © 2011-2022 走看看