如何使用log4j根据源调用类输出到文件

时间:2018-03-15 16:23:22

标签: java spring architecture

我有一个常见的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豆)

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'记录器的输出重定向到不同的日志文件,具体取决于调用类是什么?

提前致谢。

1 个答案:

答案 0 :(得分:0)

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

1)在方法调用中传入Logger 要么 2)DAO具有不同的标记接口,弹簧注入不同的记录器。

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