【问题标题】:How to output to file depending on source calling class using log4j如何使用 log4j 根据源调用类输出到文件
【发布时间】:2019-04-25 12:56:51
【问题描述】:

我有一个通用的 DAO 类,记录器由其名称初始化。

我有这样的事情:

public class QueueDaoImpl implements QueueDao {

private static Logger log = LoggerFactory.getLogger(QueueDaoImpl.class);

@Autowired
private StoredProcedureFactory storedProcedureFactory;

@Override
@Transactional(readOnly = true, value = "transactionManager")
public EnqueueRespVO enqueueMessage(EnqueueMsgReqVO req) throws DAOException {

    EnqueueRespVO toResponse;

    try {
        EnqueueMessageStoredProcedure sp = storedProcedureFactory.getEnqueueMessageSP();
        Map<String, String> inParams = BeanUtils.describe(req);

        Map<String, Object> out = sp.execute(inParams);

        toResponse = new EnqueueRespVO();

        toResponse.setErrCode((Integer) out.get(EnqueueMessageStoredProcedure.ERROR_CODE_OUT_PARAM));
        toResponse.setErrDescription((String) out.get(EnqueueMessageStoredProcedure.ERROR_DESC_OUT_PARAM));

    } catch (DataAccessException e) {
        final String msg = String.format("A database error has occurred. Error = ", e);
        //log.error("[login] - Ended with an error. ", msg);
        throw new DAOException(msg, e);
    } catch (IllegalStateException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        final String msg = String.format("A internal error has occurred. Error = ", e);
        //log.error("[login] - Ended with an error. ", msg);
        throw new DAOException(msg, e);
    }

    return toResponse;
    }
}

然后,我有两个类(发布在下面),“RetryCallUssdJob”和“SendErrorDetail”,它们使用“QueryDaoImpl”作为组合对象来执行数据库逻辑。

(我正在使用 Spring 注入 Dao bean)

RetryCallUssdJob 类的示例

@Component
public class RetryCallUssdJob {

    private static Logger log = LoggerFactory.getLogger(RetryCallUssdJob.class);

    @Autowired
    private QueueDao queueDao;

    public synchronized void execute() {
        here i'm using the queueDao instance injected by the spring context
    }
}

SendErrorDetail 类示例

 public class SendErrorDetailHandlerImpl implements ISendErrorDetailHandler {

    private static Logger log = LoggerFactory.getLogger(SendErrorDetailHandlerImpl.class);

    @Autowired
    private QueueDao queueDaoImpl;

    @Override
    public BaseRespVO execute(Map<String, Object> params) {
        here i'm using the queueDao instance injected by the spring context
    }
}

我想知道如何根据调用类将“QueryDaoImpl”记录器的输出重定向到不同的日志文件?

提前致谢。

【问题讨论】:

    标签: java spring architecture


    【解决方案1】:

    这很棘手,我会做以下两件事之一:

    1) 在方法调用中传入 Logger 或者 2) 有不同的 DAO 标记接口,由 spring 注入不同的记录器。

    1 更容易,2 更具声明性。

    【讨论】:

    • 谢谢 Rob,是的,第一个很容易实现,但考虑到提到的架构,这样做是一个好习惯吗?
    • 当然,没有理由不这样做。大多数人不会传递记录器,因为它不方便,而 Log4J 可以很容易地从类中获取它,因此无需传递它们。但是,从纯粹的 IOC 角度来看,记录器应该来自外部世界。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    相关资源
    最近更新 更多