Android Log Frame Darks-logs Tutorial

Source: Internet
Author: User
Tags log4j

Darks-logs is an Android, JAVA, web-common logging component that is similar in configuration to log4j, but it has the features of lighter weight, greater ease of use, high scalability, and support for moving ends. According to the official website, its original design goal is to provide a unified and valid log component library for Java, Web application and mobile side porting.

Project Open Source Address

Project Publishing Address
One, configuration file

Before using darks-logs, we need to create a configuration file named Logd.properties for it. If you need to use this component in Java or on the Web, you can put it in classpath as you would configure log4j.

If you use this component on the Android side, you need to place the Logd.properties file in the assets directory so that the component can find it. After placing the logd.properties file, in order for the component to get to the configuration file in the assets directory, you need to make the relevant settings in the Android application. If the Android application ANR exception information that requires log output capture, it also needs to register the ANR exception handler in application.

public class CustomApplication extends application
{
      @Override public
      void OnCreate ()
      {
	  // You must first set the Application object
          Logger.Android.setApplication (this);
	  Register ANR Error Processor
          Logger.Android.registerCrashHandler ();
          Super.oncreate ();
      }
You can set callback in the Registercrashhandler method if you want the Android application to be able to callback execution-related code after capturing the ANR exception.

Logger.Android.registerCrashHandler (New CallBack () {
      @Override public
      boolean handlemessage (msg)
      {
	   ////Execute
           New Thread () {public
               void Run () {
                    looper.prepare (
                    ) When ANR exception occurs); Toast.maketext (Customapplication.this, "The crash has happened.", Toast.length_long). Show ();
                    Looper.loop ();
               }
           . Start ();
           Thread.Sleep (3000);
           return true;
      }
  });

The default profile loader loads configuration files from Java Classpath and Android assets, if you need to load configuration files from other special locations (such as SDcard, Raw, and so on). You can customize the loader and pass Logger.Config.setCustomLoader (...) is set. The customization of the load path is increased in subsequent versions, eliminating the need for custom loaders unless you have special requirements.

second, simple use

Once the configuration file is placed and the necessary parameters are configured, we can add the configuration parameters to the configuration file.

Let's simply add a console log processor to the logd.properties.

Logd.root=info,console
#logd. Appender.console=darks.log.appender.impl.consoleappender
Logd.appender.console=consoleappender
logd.appender.console.layout=patternlayout
Logd.appender.console.layout.pattern=%d{yyyy-mm-dd HH:mm:ss}%c{1}-%m%n
Then we create a logger in the Java class and set the static variable to improve efficiency.

static Logger log = Logger.getlogger (Testlogger.class);
static Logger log = Logger.getlogger ("Darks.logs.test.TestLogger");
static Logger log = Logger.getlogger ("Testlogger");
After that, we can output log information from different log levels in a variety of ways.

Log.debug ("This are the darks logs Hello world.");
Log.info ("info message would be output");
Log.error ("happen a exception.") Cause "+ e.getmessage (), E);
If you need to do more string concatenation, or some of the log Information format. Such a way of output can improve the efficiency of a part.

Log.append ("Darks"). Append ('-'). Append ("Logs"). info ();
Log.append (2014). Append (1). Append (1). Debug (e);
Log.buffer (2014, "Coming", "now"). Warn ();
Log.format ("Darks-logs is created in%d by%s", 2014, "Darks"). Error (e);
Log.append ("..."). Append ("..."). Format ("...", ...). info ();

third, the log message format in simple use we set up a console log output, which configured the

Logd.appender.console.layout.pattern=%d{yyyy-mm-dd HH:mm:ss}%c{1}-%m%n
This configuration information is configured to configure the log format of the current message renderer. The related format is defined as follows.

%n,%n: Output a carriage return character.
%m,%m: Output message content. (also includes exception stack information)
%e,%e: Output error exception stack information.
%d,%d: output date format information, such as "%d{yyyy-mm-dd HH:mm:ss}".
%c:     output namespace or tags. We can use the%c{layer to output the information specified in the namespace.
        for example,%c{1}, if the namespace is Darks.log.DemoMain, then it will output demomain.
%c:     Output class name. You can also use the%c{number of layers} to output the specified layer of the class name.
        For example%c{2}, if the class full name is Darks.log.DemoMain, then it will output log.demomain.
%f,%f: output source file name.
%l:     output source code line number.
%l:     output time information. Includes the calling class, the thread name, the source file name, and the number of lines of code.
%p,%p: output log level.
%r,%r: Output from boot to current consumption time.
%t,%t: Outputs the current thread name.

For example:
Logd.appender.console.layout.pattern=%d{yyyy-mm-dd HH:MM:SS} [%f][%p]-%m%n
Logd.appender.console.layout.pattern=%d{yyyy-mm-dd HH:mm:ss}%c{2}-%m%n

four, Message Processor Appender is the base class for all message processors, which can configure layout, filter, and so on, and you can customize the output by inheriting the class, such as outputting logs to the Android UI.

1, Layout

Layout is mainly used to format messages, you can use your own darks.log.PatternLayout, darks.log.SimpleLayout, etc. layout, and you can even inherit loggerlayout custom implementation layout.

Patternlayout can output log information flexibly through output format. For example%d{yyyy-mm-dd HH:mm:ss}%c{1}-%m%n.
Simplelayout can output a simpler log I-type reverse attack. For example: Level-message
2, filter filter filters log messages through the specified rules.

Levelrangefilter can output log messages between the minimum and maximum levels.

#它将会输出debug与info等级之间的消息
Logd.appender.console=consoleappender
logd.appender.console.layout= Patternlayout
logd.appender.console.layout.pattern=%d{yyyy-mm-dd HH:mm:ss}%c{1}-%m%n
Logd.appender.console.filter=levelrangefilter
Logd.appender.console.filter.levelmin=debug
Logd.appender.console.filter.levelmax=info
Logd.appender.console.filter.accept=true
Regexmatchfilter can output log messages that match the specified regular expression.
#它将会输出匹配正则表达式darks \d+ Log Message
logd.appender.console=consoleappender
logd.appender.console.layout= Patternlayout
logd.appender.console.layout.pattern=%d{yyyy-mm-dd HH:mm:ss}%c{1}-%m%n
Logd.appender.console.filter=regexmatchfilter
logd.appender.console.filter.pattern=darks\d+
Logd.appender.console.filter.accept=true

Levelmatchfilter is able to output the message log for the logging level. Multiple levels are separated by commas.
#它将会输出debug以及info级别的消息日志
Logd.appender.console=consoleappender
logd.appender.console.layout= Patternlayout
logd.appender.console.layout.pattern=%d{yyyy-mm-dd HH:mm:ss}%c{1}-%m%n
Logd.appender.console.filter=levelmatchfilter
Logd.appender.console.filter.levels=debug,info
Logd.appender.console.filter.accept=true
3, AsyncA async log processor can asynchronously output log messages to the log processor.
Logd.appender.console.async=true

v. Various message processors 1, ConsoleappenderConsoleappender can output log messages to the command console.
Logd.appender.console=consoleappender
logd.appender.console.layout=patternlayout
Logd.appender.console.layout.pattern=%d{yyyy-mm-dd HH:mm:ss}%c{1}-%m%n

2, AndroidappenderAndroidappender can output messages to Android's Logcat.
Logd.appender.android=androidappender
#输出命名空间的指定层数作为logcat的TAG. The default is 1.
Logd.appender.android.layer=1
logd.appender.android.layout=patternlayout
Logd.appender.android.layout.pattern=%m

3, StreamappenderStreamappender is the underlying class for streaming output. Instead of using it directly, you must create a class that inherits from it to implement streaming output. You can use it to output messages to a file, a network, and so on.
public class Customappender extends Streamappender
{
      @Override public
      void Activatehandler ()
      {
          / /will be invoked on the first activation, you can create files with him or initialize IO streams, and so on.
      }
  
      @Override
      protected void Expandappend (LogMessage msg, String log) throws Exception
      {
          //Log extension processing here, such as check file size, etc.
      }
}

4, SocketappenderSocketappender can output log messages to the server via the TCP protocol. It inherits from Streamappender.
Logd.appender.socket=socketappender
logd.appender.socket.layout=patternlayout
Logd.appender.socket.layout.pattern=%d{yyyy-mm-dd HH:mm:ss}%c{1}-%m%n
#服务端IP
logd.appender.socket.serverhost=127.0.0.1
#服务端端口
logd.appender.socket.serverport=8686
#保持alive
logd.appender.socket.keepalive=true
logd.appender.socket.tcpnodelay=true
#用头字节封装消息, It adds a forward identity and message length to the transmitted log message.
Logd.appender.socket.wrapbytes=true

5, FileappenderFileappender can output log messages to files. It inherits from Streamappender. If you want to create a dynamic file name, you can use ${property_variable} to get the System.getproperty value. If you want to get Android's SDcard directory, you can go through ${sdcard} to get SDcard's absolute path. If you want to add a date or time to the filename, you can use the ${d[date format]}, such as ${dyyyy_mm_dd_hh_mm_ss}.
Logd.appender.file=fileappender
logd.appender.file.layout=patternlayout
Logd.appender.file.layout.pattern=%d{yyyy-mm-dd HH:mm:ss}%c{1}-%m%n
Logd.appender.file.filename=${user.dir} \log_${dyyyy_mm_dd_hh_mm_ss_ss}.txt
#logd. appender.file.filename=${sdcard}/log_${dyyyy_mm_dd_hh_mm_ss_ss}. TXT
logd.appender.file.buffered=true.

6, FiledatesizeappenderFiledatesizeappender can ensure that the log files are within the specified size and date range. The default retention time for its log file is 7 days, its default reserved size is 10MB, and a new log file is created if the specified size is exceeded. Its related attributes are inherited from Fileappender.
Logd.appender.file=filedatesizeappender
logd.appender.file.layout=patternlayout
Logd.appender.file.layout.pattern=%d{yyyy-mm-dd HH:mm:ss}%c{1}-%m%n
Logd.appender.file.filename=${user.dir} \log_${dyyyy_mm_dd_hh_mm_ss_ss}.txt
logd.appender.file.buffered=true
logd.appender.file.maxsize= 10485760
logd.appender.file.keepday=7

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.