log4j slf4j 使用和原理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011377803/article/details/79246713

一、概念理解

slf4j (Simple Logging Facade for Java) 很好理解简单日志门面。

log4j是一个日志框架,实现了slf4j 的相应接口

下面看一下slf4j的实现图,可以发现现在很多日志框架都有支持



二、使用

如果引入的slf4j的包,和log4j的包。注意版本必须配套

private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);

这里还可以使用,@Slf4j,这是一个lobmok,eclipse或者idea的一个插件。

log4j 1版本:

private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(LogUtil.class);

log4j 2版本:

private static org.apache.log4j.Logger logger = LogManager.getLogger(LogUtil.class);


三、原理

log4j-slf4j 的jar包下面。

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
package org.apache.logging.slf4j;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.spi.AbstractLoggerAdapter;
import org.apache.logging.log4j.spi.LoggerContext;
import org.apache.logging.log4j.util.ReflectionUtil;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;

/**
 * Log4j implementation of SLF4J ILoggerFactory interface.
 */
public class Log4jLoggerFactory extends AbstractLoggerAdapter<Logger> implements ILoggerFactory {

    private static final String FQCN = Log4jLoggerFactory.class.getName();
    private static final String PACKAGE = "org.slf4j";

    @Override
    protected Logger newLogger(final String name, final LoggerContext context) {
        final String key = Logger.ROOT_LOGGER_NAME.equals(name) ? LogManager.ROOT_LOGGER_NAME : name;
        return new Log4jLogger(context.getLogger(key), name);
    }

    @Override
    protected LoggerContext getContext() {
        final Class<?> anchor = ReflectionUtil.getCallerClass(FQCN, PACKAGE);
        return anchor == null ? LogManager.getContext() : getContext(ReflectionUtil.getCallerClass(anchor));
    }

}
这里可很好的看出,是log4j实现了slf4j的ILoggerFactory接口,我们开发自己的日志框架,也可以实现这个接口支持slf4j。

TODO slf4j怎么区分多个框架。

猜你喜欢

转载自blog.csdn.net/u011377803/article/details/79246713