Logging in Scala

前端 未结 14 2023
南旧
南旧 2020-12-07 06:51

What is a good way to do logging in a Scala application? Something that is consistent with the language philosophy, does not clutter the code, and is low-maintenance and uno

14条回答
  •  既然无缘
    2020-12-07 07:35

    I pulled a bit of work form the Logging trait of scalax, and created a trait that also integrated a MessageFormat-based library.

    Then stuff kind of looks like this:

    class Foo extends Loggable {
        info( "Dude, I'm an {0} with {1,number,#}", "Log message", 1234 )
    }
    

    We like the approach so far.

    Implementation:

    trait Loggable {
    
        val logger:Logger = Logging.getLogger(this)
    
        def checkFormat(msg:String, refs:Seq[Any]):String =
            if (refs.size > 0) msgfmtSeq(msg, refs) else msg 
    
        def trace(msg:String, refs:Any*) = logger trace checkFormat(msg, refs)
    
        def trace(t:Throwable, msg:String, refs:Any*) = logger trace (checkFormat(msg, refs), t)
    
        def info(msg:String, refs:Any*) = logger info checkFormat(msg, refs)
    
        def info(t:Throwable, msg:String, refs:Any*) = logger info (checkFormat(msg, refs), t)
    
        def warn(msg:String, refs:Any*) = logger warn checkFormat(msg, refs)
    
        def warn(t:Throwable, msg:String, refs:Any*) = logger warn (checkFormat(msg, refs), t)
    
        def critical(msg:String, refs:Any*) = logger error checkFormat(msg, refs)
    
        def critical(t:Throwable, msg:String, refs:Any*) = logger error (checkFormat(msg, refs), t)
    
    }
    
    /**
     * Note: implementation taken from scalax.logging API
     */
    object Logging {  
    
        def loggerNameForClass(className: String) = {  
            if (className endsWith "$") className.substring(0, className.length - 1)  
            else className  
        }  
    
        def getLogger(logging: AnyRef) = LoggerFactory.getLogger(loggerNameForClass(logging.getClass.getName))  
    }
    

提交回复
热议问题