简体   繁体   中英

Suppress spring boot printing error to stderr

I have a try/catch/finally block in the entry point to my service (the class that polls an item from SQS).
I want to catch every exception thrown from within my service and throw it out, so SQS can re-drive it.
However, this also causes the spring boot container to print the stack trace to the console, which in turn logs it into my log aggregator.
I already have an infra for meaningful logging, which adds important metadata to every log message using MDC, and hence I'd like to use it when logging the exception.

This is my code:

@SqsListener(value = "${src.queue.name}", deletionPolicy = SqsMessageDeletionPolicy.NO_REDRIVE)
public void consume(String msgJson) {
    String awsKeyJson = JsonUtils.fromJson(msgJson).get("Message").asText();
    String awsKey = JsonUtils.fromJson(awsKeyJson, AwsKey.class).getKey();
    ScanResponseContainer src = s3.getResourceAsObject(SRC_BUCKET_NAME, awsKey, ScanResponseContainer.class);
    mdcService.initializeMDC(src, awsKey);
    logger.info("Received Scan Response Container from SQS");

    try {
        ScannedMerchant sm = scanResponseContainerService.handleScanResponseContainer(src);
        producer.produce(sm);
        logger.info("Successfully processed Scan Response Container");
    } catch (Exception e) {
        throw new RuntimeException("Error thrown when processing Scan Response Container", e);
    } finally {
        mdcService.clearMDC();
        eventCollector.clear();
    }
}

My problem is - I can add to the catch block:

logger.error(e);

And it would log the error with a meaningful log message.
However, it would still log the "unmeaningful" message, because spring would still print it to the console, and then I'll get duplicate messages in my log aggregator.
Is there some kind of interceptor I can use that will still throw the exception but suppress printing the stack trace to stderr?

You can set the log level for the spring boot packages. For properties file can you set

logging.level.org.springframework=TRACE

If you have xml for logger configuration

<logger name="org.springframework" level="trace" additivity="false">
    <appender-ref ref="RollingFile" />
    <appender-ref ref="Console" />
</logger>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM