简体   繁体   English

(Java SE / Android)跨平台日志记录

[英](Java SE/Android) cross platform logging

I want this library I'm working on to have logging support, but Android and SE have their own ways of logging. 我想要这个库,我正在努力获得日志记录支持,但Android和SE有自己的日志记录方式。 In SE you can use System.out.println methods or the java.util.logging.Logger class. 在SE中,您可以使用System.out.println方法或java.util.logging.Logger类。 Android uses android.util.Log to log on logcat. Android使用android.util.Log登录logcat。 At first I used reflection to check if android was usable, then reflectively call the log methods in Log.class ; 起初我使用反射来检查android是否可用,然后反射性地调用Log.class的日志方法; but that wasn't a good idea. 但这不是一个好主意。

My solution is to have the developers using my library handle logs themselves. 我的解决方案是让开发人员使用我的库处理日志。 There will be a Handler interface they set and has an onLog method 他们将设置一个Handler接口并具有onLog方法

public void onLog(int level, String tag, String msg);

The library will call the onLog method on the handlers in my custom Logger class. 该库将在我的自定义Logger类中的处理程序上调用onLog方法。 Is it a good idea to have developers handle the logs instead of the library itself? 让开发人员处理日志而不是库本身是一个好主意吗? Seems to be the best solution so far and if I document it good then it should't be an issue. 到目前为止似乎是最好的解决方案,如果我把它记录好,那么它应该不是问题。

I agree with you that logging should be delegated to clients, and your homegrown approach is indeed sensible. 我同意你的观点,即应该将日志记录委托给客户,而你自己开发的方法确实合情合理。

IMO, the SLF4J facade would be ideal for your situation. IMO, SLF4J门面将是您的理想选择。 Your library would include the slf4j-api jar and contain SLF4J logging statements. 您的库将包含slf4j-api jar并包含SLF4J日志记录语句。 If clients wanted logging, they'd just drop in a logging backend (and an optional config file) into their application's classpath to capture/view your log statements. 如果客户希望记录,他们只需将日志记录后端(和可选的配置文件)放入其应用程序的类路径中以捕获/查看日志语句。

The advantages to this approach are that it grants clients the most control with zero coding required to get logging; 这种方法的优点是它可以为客户提供最大程度的控制,并且无需编码即可获得日志记录; and that it allows the client to choose among many available backends. 并且它允许客户端在许多可用的后端中进行选择。

I would use logback as the backend for J2SE apps and logback-android for Android. 我会使用logback作为J2SE应用程序的后端和logback-android

You can try microlog 你可以试试microlog

http://code.google.com/p/microlog4android/ http://code.google.com/p/microlog4android/

It can help you use a consistent logging mechanism across android and java. 它可以帮助您在android和java上使用一致的日志记录机制。 If you use slf4j, it can be used as a wrapper both for microlog (in case of your android project) and log4j (for your java projects) 如果你使用slf4j,它可以用作microlog(在你的android项目中)和log4j(对于你的java项目)的包装器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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