Kotlin记录器 – 记录到文件

class LogToFile(context: Context) { companion object: KLogging() val formatter = SimpleFormatter() // val logger = LoggerFactory.getLogger("MyLog") **WITH THIS LINE...** val logger = Logger.getLogger("MyLog") //this line WORKS val dest = context.applicationContext.getExternalFilesDir(null); val fh = FileHandler(dest.path.plus(File.pathSeparator).plus("data.txt")) init { //..THIS LINE DOESN'T WORK (NO addHandler is there some ekvivalent for the LoggerFactory?)// logger.addHandler(fh) fh.formatter = formatter } fun write(logString: String) { try { logger.info(logString) } catch (e: SecurityException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } } } 

**这是一个正在运行的代码,它将一个日志写入一个文件。

在过去的几天里,我一直无法find方法,如何用KotlinLogger做同样的事情。

我正在尝试将所有日志写入文件。

我是一个编码初学者,所以我希望这个问题写得够好。 如果不是,我会完成它。

我一直在Google如何做到这一点,我什么也没有find,所以我希望这是可能的。

正在工作的记录器是’java.util.logging.Logger’我想要使用的是’mu.KLogging’(或可能是’org.slf4j.LoggerFactory’)

更新:我发现这个: https : //github.com/tony19/logback-android/wiki目前正在实施:

  implementation 'io.github.microutils:kotlin-logging:1.4.9' implementation 'org.slf4j:slf4j-api:1.7.25' compile 'com.github.tony19:logback-android-core:1.1.1-6' compile('com.github.tony19:logback-android-classic:1.1.1-6') { // workaround issue #73 exclude group: 'com.google.android', module: 'android' 

现在简单地登录到日志猫的作品。 仍然在将日志写入文件。 **

所以,我设法登录到logcat和一个文件。 由于我从来没有发现这个问题在其他地方解决,我在这里张贴,以防有人需要它的时候。

我编译了这些在我的gradle文件中:

 dependencies { compile 'io.github.microutils:kotlin-logging:1.4.9' compile 'org.slf4j:slf4j-api:1.7.25' compile 'com.github.tony19:logback-android-core:1.1.1-6' compile('com.github.tony19:logback-android-classic:1.1.1-6') { // workaround issue #73 exclude group: 'com.google.android', module: 'android' } implementation 'org.slf4j:slf4j-api:1.7.25' implementation 'log4j:log4j:1.2.17' 

我在日志记录类中使用了一个伴侣对象:

 import mu.KLogging class LogToFile(context: Context) { companion object: KLogging() fun write(){ logger.info("Hello World")} } 

并创建了一个logback.xml配置文件:

     ${USER_HOME}/myApp.log   %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n      %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n       

所以它现在写入一个文件和一个logcat,一切正常。