Koustav Ray Koustav Ray - 1 month ago 13
Java Question

Logback giving error Cannot cast object '3 gb' with class 'java.lang.String' to class 'ch.qos.logback.core.util.FileSize'

I have a springboot application and while trying to log using logback with groovy config I am getting following error:

Failed to instantiate [ch.qos.logback.classic.LoggerContext]
Reported exception:
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '3 gb' with class 'java.lang.String' to class 'ch.qos.logback.core.util.FileSize'
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnSAM(DefaultTypeTransformation.java:405)
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnNumber(DefaultTypeTransformation.java:319)


My groovy config file:

import ch.qos.logback.classic.PatternLayout
import static ch.qos.logback.classic.Level.INFO

scan("60 seconds")
def LOG_PATH = "logs"
def LOG_ARCHIVE = "${LOG_PATH}/archive"



appender("RollingFile-Appender", RollingFileAppender) {
file = "${LOG_PATH}/rollingfile.log"
rollingPolicy(TimeBasedRollingPolicy) {
fileNamePattern = "${LOG_ARCHIVE}/Rainbow_Notifications.log%d{yyyy-MM-dd}.log"
maxHistory = 30
totalSizeCap = "3 gb"
}
encoder(PatternLayoutEncoder) {
pattern = "%msg%n"
}
}


logger("com.something", INFO, ["RollingFile-Appender"])


Note: I have tried even these strings:as file size:
3gb
,
3 gb
,
3GB
,
3096mb
,
3096 mb
,
3096 MB

Answer Source

Try replacing the line

    totalSizeCap = "3 gb"

with

    totalSizeCap = FileSize.valueOf("3 gb")

You'll need to add the line import ch.qos.logback.core.util.FileSize; as well.

The setTotalSizeCap method of the TimeBasedRollingPolicy class takes a FileSize object, not a string. The static valueOf method in FileSize should do the necessary conversion from string to FileSize.