Home > OS >  Suppress spring boot printing error to stderr
Suppress spring boot printing error to stderr

Time:02-11

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?

CodePudding user response:

You can set the log level for the spring boot packages. For properties file can you set it to OFF or FATAL.

logging.level.org.springframework=OFF

If you have xml for logger configuration

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

Logback update: Spring Documentation
Logback Level

Stackoverflow : Logback level off issue.

  • Related