簡體   English   中英

使用java注釋注入logger依賴項

[英]Using java annotation to inject logger dependency

我使用帶有aspect-j注釋支持的@Loggable來允許@Loggable注釋。 這允許基於配置自動登錄類。

我想知道我是否可以以某種方式使用此注釋將slf4j Logger變量暴露給類以供直接使用,這樣我就不必對以下內容執行某些操作:

Logger logger = LoggerFactory.getLogger(MyClass.class);

如果上面因為注釋而隱式可用,那將是很好的,我可以去做logger.debug("..."); 沒有聲明。 我不確定這是否可行。

您可以使用BeanPostProcessor接口,該接口由ApplicationContext為所有創建的bean調用,因此您有機會填充相應的屬性。

我創建了一個簡單的實現,它可以做到:

import java.lang.reflect.Field;
import java.util.List;

import net.vidageek.mirror.dsl.Mirror;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class LoggerPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        List<Field> fields = new Mirror().on(bean.getClass()).reflectAll().fields(); 
        for (Field field : fields) {
            if (Logger.class.isAssignableFrom(field.getType()) && new Mirror().on(field).reflect().annotation(InjectLogger.class) != null) {
                new Mirror().on(bean).set().field(field).withValue(LoggerFactory.getLogger(bean.getClass()));
            }
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

您不必執行任何復雜的注冊步驟,因為ApplicationContext能夠識別BeanPostProcessor實例並自動注冊它們。

@InjectLogger注釋是:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface InjectLogger {
}

然后您可以輕松使用注釋:

public static @InjectLogger Logger LOGGER;

...

LOGGER.info("Testing message");

我使用鏡像庫來查找帶注釋的字段,但顯然您可以執行手動查找以避免這種額外的依賴性。

實際上,避免重復代碼,甚至是從其他類復制和粘貼Logger定義所產生的小問題也是一個好主意,比如當我們忘記更改class參數時,這會導致錯誤的日志。

你無法用一個方面做到這一點,但是可以幫助你,在我看來,優雅的方式。 請參閱@Log注釋。

我認為@Redder的解決方案是一種很好的方法。 但是,我不想包含鏡像庫,因此我編寫了一個使用Java反射庫的LoggerPostProcessor實現。 這里是:

package com.example.spring.postProcessor;

import com.example.annotation.InjectLogger;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class LoggerPostProcessor implements BeanPostProcessor {

    private static Logger logger = LoggerFactory.getLogger(LoggerPostProcessor.class);

    /* (non-Javadoc)
     * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object, java.lang.String)
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        List<Field> fields = Arrays.asList(bean.getClass().getDeclaredFields());

        for (Field field : fields) {
            if (Logger.class.isAssignableFrom(field.getType()) && field.getAnnotation(InjectLogger.class) != null) {

                logger.debug("Attempting to inject a SLF4J logger on bean: " + bean.getClass());

                if (field != null && (field.getModifiers() & Modifier.STATIC) == 0) {
                    field.setAccessible(true);
                    try {
                        field.set(bean, LoggerFactory.getLogger(bean.getClass()));
                        logger.debug("Successfully injected a SLF4J logger on bean: " + bean.getClass());
                    } catch (IllegalArgumentException e) {
                        logger.warn("Could not inject logger for class: " + bean.getClass(), e);
                    } catch (IllegalAccessException e) {
                        logger.warn("Could not inject logger for class: " + bean.getClass(), e);
                    }
                }
            }
        }

        return bean;
    }

    /* (non-Javadoc)
     * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object, java.lang.String)
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

}

我想對@Redder的解決方案做一些改進。

  • 首先 - 我們可以省略新注釋@Log引入,而是我們可以使用Spring的@Autowired注釋,並將'required'標志設置為'false',以使Spring不檢查是否注入了bean(因為,我們稍后會注入它) )。
  • 第二 - 使用Spring的ReflectionUtils API,它提供了字段發現和操作所需的所有方法,因此我們不需要額外的外部依賴。

這里有一個例子(在Java 8中,但可以在Java slf4j /等中重寫,也使用了slf4j facade,但它可以替換為任何其他記錄器):

@Component
public class LoggerPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        Logger logger = getLogger(bean.getClass());
        doWithFields(bean.getClass(), field -> {

            makeAccessible(field);
            setField(field, bean, logger);

        }, field -> field.isAnnotationPresent(Autowired.class) && Logger.class.equals(field.getType()));

        return bean;
    }
    ...
}
...
//logger injection candidate
@Autowired(required = false)
private Logger log;

因為我在嘗試在CDI (JSR 299:上下文和依賴注入)中做同樣的事情時得到了這個結果, 這個鏈接顯示了使用CDI (以及使用Spring的替代方法) 這樣做的簡單方法

基本上,你只需要注入:

class MyClass {
   @Inject private Log log;

並有一個像這樣的記錄器工廠:

@Singleton
public class LoggerFactory implements Serializable {
    private static final long serialVersionUID = 1L;

    static final Log log = LogFactory.getLog(LoggerFactory.class);

   @Produces Log createLogger(InjectionPoint injectionPoint) {
    String name = injectionPoint.getMember().getDeclaringClass().getName(); 
    log.debug("creating Log instance for injecting into " + name); 
    return LogFactory.getLog(name);
    }   
}

我發現我需要在注入的log添加transient ,以便在我的會話范圍bean中沒有得到鈍化范圍異常:

@Named()
@SessionScoped()
public class MyBean implements Serializable {
    private static final long serialVersionUID = 1L;

    @Inject
    private transient Log log;

Herald提供了一個非常簡單的BeanPostProcessor,它為您提供了所有的魔力。 您可以使用@Log注釋來注釋Spring bean的任何字段,以使Herald在此字段中注入合適的記錄器。

支持的日志框架:

  • JavaTM 2平台的核心日志框架
  • Apache Commons Logging
  • 簡單的Java日志記錄(SLF4J)
  • SLF4J擴展記錄器
  • 的logback
  • Apache Log4j
  • Apache Log4j 2
  • JBoss日志記錄
  • Syslog4j
  • 來自Graylog的Syslog4j分叉
  • 適用於Java的Fluent Logger

還可以添加其他日志框架。

Github回購: https//github.com/vbauer/herald

這是一篇博客文章,其中包含一個包含所有代碼的完整示例: 使用Spring注入記錄器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM