Giter Site home page Giter Site logo

noveogroup / android-logger Goto Github PK

View Code? Open in Web Editor NEW
223.0 23.0 49.0 1.69 MB

Useful logger for Android based on standard android.util.Log class. Simple lightweight (< 50 Kb) implementation of SLF4J API. Easy but powerful configuration via properties file and some additional helpful logging methods. Easy analogue of popular log4j library.

Home Page: https://noveogroup.github.io/android-logger

License: Other

Java 100.00%

android-logger's Introduction

Android Logger

Useful logger for Android based on standard android.util.Log class. Simple lightweight (< 50 Kb) implementation of SLF4J API. Easy but powerful configuration via properties file and some additional helpful logging methods. Easy analogue of popular log4j library.

Android SDK Version: API 7 [ Android 2.1 ]

Code Samples: [here]

Android Arsenal

Downloads

Maven Dependency

<dependency>
    <groupId>com.noveogroup.android</groupId>
    <artifactId>android-logger</artifactId>
    <version>1.3.5</version>
</dependency>

Gradle Dependency

'com.noveogroup.android:android-logger:1.3.5'

Getting Started

If you want to use Android Logger in your Android application you need to do just the following simple steps:

  • Add Android Logger as a library OR add it as Maven or Gradle dependency.

  • Configure Android Logger.

Place the following android-logger.properties file to your source directory (src/main/resources/android-logger.properties):

# Android Logger configuration example

# By default logger will print only ERROR (and higher) messages
# with "MyApplication" tag
root=ERROR:MyApplication

# DEBUG (and higher) messages from classes of com.example.database
# will be logged with "MyApplication-Database" tag
logger.com.example.database=DEBUG:MyApplication-Database

# All messages from classes of com.example.ui will be logged with
# "MyApplication-UI" tag
logger.com.example.ui=MyApplication-UI

The configuration manages which log tag will be used to print messages and which logging level filter will be applied.

logger.<package/classname>=<level>:<tag>:<message head>
# or
logger.<package/classname>=<level>:<tag>
# or
logger.<package/classname>=<tag>

The rest of messages will be managed by root logger:

root=<level>:<tag>:<message head>
# or
root=<level>:<tag>
# or
root=<tag>

You can use VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT as level in configuration files.

Format of and is desribed below in Patterns section.

  • You need to get logger instance to print messages

You can use LoggerManager to get a logger instance to print messages.

package com.example.ui;

import com.noveogroup.android.log.Logger;
import com.noveogroup.android.log.LoggerManager;

public class MainActivity extends Activity {

  // get a logger instance by name
  private static final Logger logger = LoggerManager.getLogger("com.example.ui.MyActivity");
  // get a logger instance by class
  private static final Logger logger = LoggerManager.getLogger(MainActivity.class);
  // just to use current class
  private static final Logger logger = LoggerManager.getLogger();

  private void foo(int value) {
    logger.i("entered MainActivity::foo value=%d", value);
    
    try {
      // some code
    } catch(IOException e) {
      logger.e("I/O error occurred", e);
    }
  }

}
  • You can use Log class to make logging calls shorter.

Any call like Log.someMethod() is equal to LoggerManager.getLogger().someMethod(). So, there will be some additional overhead to get a logger each time.

import com.noveogroup.android.log.Log;

public class Bar {

  public void foo() {
    Log.i("some log message");
  }

}

Patterns

You can configure format of tags and messages headers in your configuration file.

For example, the following configuration file:

logger.ROOT=INFO:MyApplication:%caller{-2}

will generate the following output:

PatternTest#<init>:15 your message

So, the logger insert inforation about caller before the message.

The patterns are format strings written according to a special rules described below. Log messages will be formatted and printed as it is specified in the tag and the message pattern. The tag pattern configures log tag used to print messages. The message pattern configures a head of the message but not whole message printed to log.

The tag pattern The message pattern Resulting tag Resulting message
TAG %d{yyyy-MM-dd}: TAG %d{yyyy-MM-dd}:

The tag and the message patterns are wrote according to similar rules. So we will show only one pattern in further examples.

The patterns is strings that contains a set of placeholders and other special marks. Each special mark should start with '%' sign. To escape this sign you can double it.

Conversion marks

Mark %%

Escapes special sign. Prints just one '%' instead.

Mark %n

Prints a new line character '\n'.

Marks %d{date format} and %date{date format}

Prints date/time of a message. Date format should be supported by SimpleDateFormat. Default date format is "yyyy-MM-dd HH:mm:ss.SSS".

Marks %p and %level

Prints logging level of a message.

Marks %c{count.length} and %logger{count.length}

Prints a name of the logger. The algorithm will shorten some part of full logger name to the specified length. You can find examples below.

Conversion specifier Logger name Result
%logger com.example.android.MainActivity com.example.android.MainActivity
%logger{0} com.example.android.MainActivity com.example.android.MainActivity
%logger{3} com.example.android.MainActivity com.example.android
%logger{-1} com.example.android.MainActivity example.android.MainActivity
%logger{.0} com.example.android.MainActivity com.example.android.MainActivity
%logger{.30} com.example.android.MainActivity com.example.android.*
%logger{.15} com.example.android.MainActivity com.example.*
%logger{.-25} com.example.android.MainActivity *.android.MainActivity
%logger{3.-18} com.example.android.MainActivity *.example.android
%logger{-3.-10} com.example.android.MainActivity$SubClass MainActivity$SubClass
Marks %C{count.length} and %caller{count.length}

Prints information about a caller class which causes the logging event. Additional parameters 'count' and 'length' means the same as the parameters of %logger.

Examples:

Conversion specifier Caller Result
%caller Class com.example.android.MainActivity at line 154 com.example.android.MainActivity:154
%caller{-3.-15} Class com.example.android.MainActivity at line 154 MainActivity:154
Marks %s and %source

Prints source of class which causes the logging event.

Examples:

Conversion specifier Caller Result
%source or %s Class com.example.android.MainActivity at line 154 (MainActivity.java:154)
%source or %s Native (native)
%source or %s Unknown (unknown)
Marks %t and %thread

Prints a name of the thread which causes the logging event.

Mark %(...)

Special mark used to grouping parts of message. Format modifiers (if specified) are applied on whole group.

Examples:

Example Result
[%50(%d %caller{-3.-15})] [ 2013-07-12 19:45:26.315 MainActivity:154]
[%-50(%d %caller{-3.-15})] [2013-07-12 19:45:26.315 MainActivity:154 ]

Format modifiers

After special sign '%' user can add format modifiers. The modifiers is similar to standard modifiers of Formatter conversions.

Example Result
%6(text) ' text'
%-6(text) 'text '
%.3(text) 'tex'
%.-3(text) 'ext'

For an additional information see sources of com.noveogroup.android.log.PatternHandler class

SLF4J compatibility

Android Logger is SLF4J compatible. For example, you can write such code in your library:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Bar {

  private static final Logger logger = LoggerFactory.getLogger(Bar.class);

  public void foo(int value) {
    logger.info("entered Bar::foo value={}", value);

    try {
      // some code
    } catch(IOException e) {
      logger.error("I/O error occurred", e);
    }
  }

}

Suppose you compiled your library as JAR-file and publish it. After that anyone who uses your JAR library will be able to add any SLF4J implementation to change the way how the library logs messages. The most powerful implementation of SLF4J is LOGBack available for Android. Unfortunately, it has about 1 Mb size and it may be critical for some Android applications. Android Logger is SLF4J compatible too. So you can just add its JAR as a library to get all your log messages in Android LogCat.

Developed By

License

Copyright (c) 2013 Noveo Group

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

android-logger's People

Contributors

bitdeli-chef avatar kurumar avatar miensol avatar vbauer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

android-logger's Issues

properties file location

Hi,

We've tried putting the android-logger.properties file in the src folder and a lot others, but we always get the "Logger configuration file is empty. Default configuration will be used" message. Would you have any other suggestions?

We are using gradle and Android Studio if that helps.

Thank you.

Patterns with {sign count} does not work

Using Gradle dependency 'com.noveogroup.android:android-logger:1.3.1'

Into android-logger.properties

root=DEBUG:Euro01:%C gives "D/Euro01: com.example.olivier.euro01.CoinActivity6Fragment.trace2(CoinActivity6Fragment.java:74) onCreate"
Seems ok (but is it normal that source is output ?)

root=DEBUG:Euro01:%C{2} gives "D/Euro01: com.example onCreate"
root=DEBUG:Euro01:%C{3} gives "D/Euro01: com.example.olivier onCreate"
root=DEBUG:Euro01:%caller{3} gives "D/Euro01: com.example.olivier onCreate"
Seems ok

root=DEBUG:Euro01:%caller{-3} gives "D/Euro01: com.example.olivier.euro01.CoinActivity6Fragment.trace2(CoinActivity6Fragment.java:74){-3} onCreate"
root=DEBUG:Euro01:%caller{+3} gives "D/Euro01: com.example.olivier.euro01.CoinActivity6Fragment.trace2(CoinActivity6Fragment.java:74){+3} onCreate"
NOT ok, com.example.olivier not removed AND {-3} printed

App crash due to format exception

Log.a("jsonResponse" + jsonResponse);

This caused the below crash:
java.util.MissingFormatArgumentException: Format specifier: 3a
at java.util.Formatter.getArgument(Formatter.java:1111)
at java.util.Formatter.doFormat(Formatter.java:1076)
at java.util.Formatter.format(Formatter.java:1042)
at java.util.Formatter.format(Formatter.java:1011)
at java.lang.String.format(String.java:1803)
at java.lang.String.format(String.java:1777)
at com.noveogroup.android.log.PatternHandler.print(PatternHandler.java:355)
at com.noveogroup.android.log.SimpleLogger.print(SimpleLogger.java:63)
at com.noveogroup.android.log.AbstractLogger.a(AbstractLogger.java:167)
at com.noveogroup.android.log.Log.a(Log.java:313)
at com.myapp.APIController$13.onResponse(ChatController.java:696)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:170)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)

Is this a known bug? I'm running latest version.

Implement an easy way to switch to LOGBack

This library is "little LOGBack". So it should implement some easy way to switch without a lot of configurations and so on.

For example:
User log messages via our classes and can set some flag to true and start using LOGBack via our classes.

How to disable the log level

Hi, i want to disable all logging levels including VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT in the release version. How can i configure it in the android_properties file. Thanks

There is an exception

There is an exception when i call

 logger.d("80%");

java.util.UnknownFormatConversionException

Feature: Dynamic tags

Can the tag be "dynamically" set? Maybe something like:

Properties:

# All classes in the following package will use the String or class as the logging tag
logger.com.example.activity=DEBUG:*

Code:

// TAG = MainActivity
private static final Logger LOG = LoggerManager.getLogger(MainActivity.class);

// TAG = "@@@@@@@"
private static final Logger LOG = LoggerManager.getLogger("@@@@@@@");

This would make the library extremely more useable for larger projects without defining different tags for packages or if you need to target certain classes quickly.

Improve configuration

  1. Implement configuration changes (see them below).
  2. Implement formatting (#1).
  3. Write special section in README about formatting.
  4. Update section "configuration" in README.
  5. Update samples.
  6. Test changes.
  7. Release new version

New configuration principals:

  1. There is a logger's hierarchy which is like package hierarchy.
  2. On each its level we can place filter or printer or both.
  3. Filter - filter log messages, thank you cap.
  4. Printer - prints messages.
  5. Messages are printed only once (todo discuss).
  6. Printers are configured with format string for tag and messages.

%caller and %source do not work properly with slf4j

When using the SLF4J bindings, both %caller and %source always results in AndroidLoggerAdapter as the caller/source instead of the actual class that the SLF4J log call was done in.

#android-logger.properties file
logger.com.example=DEBUG:Example:[%t] %caller{-3.-15}%source
//SLF4J test
private static final Logger log = LoggerFactory.getLogger(MainActivity.class);

public void doTest() {
    log.info("Testing");
}
05-19 09:23:45.129 736-804/com.example.activity D/Syncronous: [main] AndroidLoggerAdapter#log:55(AndroidLoggerAdapter.java:55) Testing

tag from classname

In logback-android, the 'tag' comes from the name of the class passed to Logger.getLogger. However, in android-logger the 'tag' has to be hard-coded in android-logger.properties.

There should be a way to specify that we want to use the classname as the tag.

Duplicate entry for slf4j class - StaticLoggerBinder

Our release build fails with the following error

Warning:Exception while processing task java.io.IOException: Can't write  
    [.../app/build/intermediates/transforms/proguard/release/jars/3/1f/main.ja] 
    (Can't read [.../.gradle/caches/modules-2/files 
2.1/com.noveogroup.android/android-
logger/1.3.6/5cb3345e23efd3d3a195eb8c4ae5b627189f8159/android-logger-
1.3.6.jar(;;;;;;**.class)] (Duplicate zip entry [org/b/c/a.class == 
android-logger-1.3.6.jar:org/slf4j/impl/StaticLoggerBinder.class]))

Looks like the internal slf4j package conflicts with other libraries depending on the slf4j library

Stack trace ignored

In AndroidLoggerAdapter.java line 100

public void trace(String msg, Throwable t) {
        log(Logger.Level.VERBOSE, msg);
}

All other log levels (all but one) has the same bug.

Cannot log content with "%" symbol.

This is using the 1.3.2 release.

Logging a message through SLF4J with a % symbol, either in the format string or argument string, results in an exception.

log.trace("This will throw {}", "Happens 100%!");

Partial stack trace:

     Caused by: java.util.MissingFormatArgumentException: Format specifier: ;
            at java.util.Formatter.getArgument(Formatter.java:1111)
            at java.util.Formatter.doFormat(Formatter.java:1076)
            at java.util.Formatter.format(Formatter.java:1042)
            at java.util.Formatter.format(Formatter.java:1011)
            at java.lang.String.format(String.java:1999)
            at java.lang.String.format(String.java:1973)
            at com.noveogroup.android.log.PatternHandler.print(PatternHandler.java:298)
            at com.noveogroup.android.log.SimpleLogger.print(SimpleLogger.java:56)
            at org.slf4j.impl.AndroidLoggerAdapter.log(AndroidLoggerAdapter.java:63)
            at org.slf4j.impl.AndroidLoggerAdapter.trace(AndroidLoggerAdapter.java:91)

Logger throws exception if API level <= 8

While initializing Logger on device with API Level 8 I get following exception:

04-17 11:25:33.598: ERROR/AndroidRuntime(336): FATAL EXCEPTION: main
java.lang.ExceptionInInitializerError
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1429)
at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ExceptionInInitializerError
at com.noveogroup.android.MainActivity.(MainActivity.java:28)
... 15 more
Caused by: java.lang.NoSuchMethodError: java.util.Properties.stringPropertyNames
at com.noveogroup.android.log.LoggerManager.loadConfiguration(LoggerManager.java:121)
at com.noveogroup.android.log.LoggerManager.(LoggerManager.java:143)
... 16 more

for this line:

private static final Logger logger = LoggerManager.getLogger();

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.