Utility logger library for storing logs into database and push them to remote server for debugging

Overview

HyperLog Android

Open Source Love License: MIT Download

Overview

A utility logger library for Android on top of standard Android Log class for debugging purpose. This is a simple library that will allow Android apps or library to store log into database so that developer can pull the logs from the database into File or push the logs to your remote server for debugging purpose. Want to know more on this and wondering why you should prefer using this library over doing it yourself. Check out the blog post or sample apk.

Device Logger

Log Format

timeStamp + " | " + appVersion + " : " + osVersion + " | " + deviceUUID + " | [" + logLevelName + "]: " + message
2017-10-05T14:46:36.541Z 1.0 | 0.0.1 : Android-7.1.1 | 62bb1162466c3eed | [INFO]: Log has been pushed

Download

Download the latest version or grab via Gradle.

The library is available on mavenCentral() and jcenter(). In your module's build.gradle, add the following code snippet and run the gradle-sync. from rest_framework import views

class SDKLogFileAPIView(views.APIView): ''' SDK Log endpoint for file uploads

Example curl call:
curl -i -X POST
        -H "Content-Type: multipart/form-data"
        -H "Authorization: token pk_e6c9cf663714fb4b96c12d265df554349e0db79b"
        -H "Content-Disposition: attachment; filename=upload.txt"
        -F "data=@/Users/Arjun/Desktop/filename.txt"
        localhost:8000/api/v1/logs/
'''
parser_classes = (
    parsers.FileUploadParser,
)

def post(self, request):
dependencies {
    ...
    compile 'com.hypertrack:hyperlog:0.0.10'
    ...
}

Don't forget to add also the following dependencies


    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.code.gson:gson:2.8.1'
   

and the following permession to AndroidManifest.xml


     <uses-permission android:name="android.permission.INTERNET" />
   

Initialize

Inside onCreate of Application class or Launcher Activity.

HyperLog.initialize(this);
HyperLog.setLogLevel(Log.VERBOSE);

Usage

HyperLog.d(TAG,"Debug Log");

Get Logs in a File

File file = HyperLog.getDeviceLogsInFile(this);

Push Logs Files to Remote Server

Logs file can be pushed to your remote server or RequestBin(for testing) or to Logstash.

Steps:

  1. Set the API Endpoint URL HyperLog.setURL before calling HyperLog.pushLogs method otherwise exception will be thrown. Developers can also set a testing endpoint using RequestBin.
HyperLog.setURL("API URL");
  1. Push Logs file to the given endpoint.
HyperLog.pushLogs(this, false, new HLCallback() {
            @Override
            public void onSuccess(@NonNull Object response) {

            }

            @Override
            public void onError(@NonNull VolleyError HLErrorResponse) {

            }
});

Follow steps to setup testing endpoint at RequestBin

  1. Visit the RequestBin site and create a RequestBin.
  2. Once you have the bin created, copy the URL and set it to the HyperLog.setURL.
  3. Now call HyperLog.pushLogs to push the logs file to given endpoint. This is asynchronous call.
  4. After HyperLog.pushLogs success, reload the requestbin page to view exactly which requests were made, what headers were sent, and raw body and so on, all in a pretty graphical setting like below image.
  5. Once you get the logs on RequestBin create your own endpoint on your server and start receiving logs on to your server for debugging.
  6. (Optional) From your server you can directly push those to Logstash (part of ELK stack). We have discussed ELK in one of our blog.

RequestBin

Request Bin Sample Response

Setup example endpoint inside Django

The example code below will set you up with a view that can handle uploaded log files, decompress gzip, and print the contents of the file.

import zlib

from backend_apps.hyperlogs.models import HyperLog

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO
import logging

logging.basicConfig()
logger = logging.getLogger(__name__)

from rest_framework import views, parsers
from rest_framework.response import Response

class SDKLogFileAPIView(views.APIView):
    '''
    SDK Log endpoint for file uploads

    Example curl call:
    curl -i -X POST
            -H "Content-Type: multipart/form-data"
            -H "Authorization: token pk_e6c9cf663714fb4b96c12d265df554349e0db79b"
            -H "Content-Disposition: attachment; filename=upload.txt"
            -F "data=@/Users/Arjun/Desktop/filename.txt"
            localhost:8000/api/v1/logs/
    '''
    parser_classes = (
        parsers.FileUploadParser,
    )

    def post(self, request):
        '''
        Prints logs to stdout (accepts file)
        '''
        if request.FILES:
            device_id = self.request.META.get('HTTP_DEVICE_ID', 'None')
            user_agent = self.request.META.get('HTTP_USER_AGENT', 'None')
            expect_header = self.request.META.get('HTTP_EXPECT', 'None')
            file_obj = request.FILES['file']
            logger.info('Received log file of size %s bytes from device id: %s and user agent: %s and expect header: %s' %
                        (str(file_obj.size), device_id, user_agent, expect_header))
            self.decompress_file(file_obj)

        return Response({})

    def decompress_file(self, f):
        '''
        Decompress the gzip file and then print it to stdout
        so that logstash can pick it up. In case Content-Encoding
        is not gzip, then the normal method picks up the file.
        '''
        if not self.request.META.get('HTTP_CONTENT_ENCODING') == 'gzip':
            return self.handle_uploaded_file(f)

        result = StringIO()

        for chunk in f.chunks():
            chunk = str(chunk, errors='ignore')
            result.write(chunk)

        stringified_value = result.getvalue()
        result.close()
        decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS)
        stringified_value = str.encode(stringified_value)
        logger.error('=================hyperlog=============')
        logger.error(stringified_value)
        decompressed = decompressor.decompress(stringified_value)

        for line in decompressed.split('\n'):
            print (line)

    def handle_uploaded_file(self, f):
        '''
        Handle django file to print, so that logstash
        can pick it up.
        '''
        for chunk in f.chunks():
            logger.error("================================hyperlog======================")
            logger.error(chunk)
            chunk = chunk.decode()
            lines = chunk.split('\n')
            logs=[]
            for line in lines:
                print (line)
                logs.append(line)
            HyperLog.objects.create(log=logs)

Note:

  • Push logs file to server in compressed form to reduce the data consumption and response time.
HyperLog.pushLogs(Context mContext, boolean compress, HyperLogCallback callback);
  • Logs will be compressed using GZIP encoding.
  • Logs will be deleted from database after successful push.
  • Logs will push to the server in batches. Each batch can have maximum of 5000 logs.

Custom Log Message Format

Default Log Message that will store in database.

timeStamp + " | " + appVersion + " : " + osVersion + " | " + deviceUUID + " | [" + logLevelName + "]: " + message
2017-10-05T14:46:36.541Z 1.0 | 0.0.1 : Android-7.1.1 | 62bb1162466c3eed | [INFO]: Log has been pushed

This message can easily be customize.

  1. Create a new class extending LogFormat.
  2. Override getFormattedLogMessage method.
  3. Now return the formatted message.
class CustomLogMessageFormat extends LogFormat {

    CustomLog(Context context) {
        super(context);
    }

    public String getFormattedLogMessage(String logLevelName, String message, String timeStamp,
                                         String senderName, String osVersion, String deviceUUID) {
                                         
        //Custom Log Message Format                                
        String formattedMessage = timeStamp + " : " + logLevelName + " : " + deviceUUID + " : " + message;
        
        return formattedMessage;
    }
}

Custom Log Message Format example

2017-10-05T14:46:36.541Z 1.0 | INFO | 62bb1162466c3eed | Log has been pushed

  1. Above created class instance then needs to be passed while initializing HyperLog or can be set later.
HyperLog.initialize(this,new CustomLogMessageFormat(this));
 
OR
 
HyperLog.initialize(this);
HyperLog.setLogFormat(new CustomLogMessageFormat(this));

Additional Methods

  • Different types of log.
HyperLog.d(TAG,"debug");
HyperLog.i(TAG,"information");
HyperLog.e(TAG,"error");
HyperLog.v(TAG,"verbose");
HyperLog.w(TAG,"warning");
HyperLog.a(TAG,"assert");
HyperLog.exception(TAG,"exception",throwable);
  • To check whether any device logs are available.
HyperLog.hasPendingDeviceLogs();
  • Get the count of stored device logs.
HyperLog.logCount();
  • Developer can pass additional headers along with API call while pushing logs to server.
HashMap<String, String> additionalHeaders = new HashMap<>();
additionalHeaders.put("Authorization","Token");
HyperLog.pushLogs(this, additionalHeaders, false, HLCallback);
  • By default, seven days older logs will get delete automatically from the database. You can change the expiry period of logs by defining expiryTimeInSeconds.
HyperLog.initialize(@NonNull Context context, int expiryTimeInSeconds);
  • Developers can also get the device log as a list of DeviceLog model or list of String .By default, fetched logs will delete from the database. Developers can override to change the default functionality.
HyperLog.getDeviceLogs(boolean deleteLogs);
HyperLog.getDeviceLogsInFile(Context mContext, boolean deleteLogs);
  • By default, every get calls return data from first batch if there are one or more batch.
  • If there are more than one batches then developer can gets the specific batch data by providing batch number.
HyperLog.getDeviceLogs(boolean deleteLogs, int batchNo);
  • Get the number of batches using HyperLog.getDeviceLogBatchCount.
  • Developer can manually delete the logs using HyperLog.deleteLogs.

Documentation For Android using Kotlin

Read the different methods and how to implement HyperLogs in Android using Kotlin here.

Contribute

Please use the issues tracker to raise bug reports and feature requests. We'd love to see your pull requests, so send them in!

About HyperTrack

Developers use HyperTrack to build location features, not infrastructure. We reduce the complexity of building and operating location features to a few APIs that just work. Sign up and start building! Join our Slack community to connect with other developers building location features. Email us at [email protected] if you need any help.

License

MIT License

Copyright (c) 2018 HyperTrack

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.

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.
Comments
  • Added documentation/blog link for android/kotlin

    Added documentation/blog link for android/kotlin

    I struggling a lot for implementing this library for android using kotlin as the blogs and other articles available are all using java and others. So wanted to help the community with the full documentation of the library for the major functions available for android w.r.t. kotlin.

    opened by thenishchalraj 5
  • Version name always returns 1.0

    Version name always returns 1.0

    I believe you can't trust BuildConfig.VERSION_NAME to return the actual version name defined in build.gradle.

    You should maybe update LogFormat to look something like this:

    public class LogFormat implements Serializable {
    
        private String deviceUUID;
        private String versionName;
    
        public LogFormat(Context context) {
            Context mContext = context.getApplicationContext();
            deviceUUID = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
            try {
                PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
                this.version = pInfo.versionName;
            } catch (PackageManager.NameNotFoundException exception) {
                this.version = "null";
            }
    }
    

    And then use this.version when building the log string.

    opened by arokanto 3
  • Where to write

    Where to write "File file = HyperLog.getDeviceLogsInFile(this);" this line of code.

    Hi,

    i want to know whether i have to write the above line of code with every custom log in android code or just one time in every activity or fragment.

    Basically tell me how this line will create on file if i write logs in different files in different packages.

    opened by Saloni123456 2
  • Log level debug and verbose incorrect when push to server

    Log level debug and verbose incorrect when push to server

    When use Hyperlog.d or Hyperlog.v to log a message and push to the server, it will use the log level I set globally for level filtering. Other log levels are ok.

    opened by timchanyiuman 1
  • Missing TAG in formatLogMessage method

    Missing TAG in formatLogMessage method

    User should have a possibility to add information about TAG and format message with TAG and send the TAG to a server because many Android devs use tags to recognize a place of logs.

    opened by mariopce 1
  • android:allowBackup=

    android:allowBackup="true" attribute in Manifest causes problems

    Hi,

    Looks like you have the above attribute in the AndroidManifest. This causes merging problems for those who have apps with allowBackup set to false. There's a way to get around it using tools:replace but I'm wondering if there's a need for it on your side (since using tools:replace effectively ignores it regardless)?

    I can quickly open up a PR if needed.

    Thanks, Julien

    opened by jguerinet 1
  • Success callback not called due to weakreference

    Success callback not called due to weakreference

    A weakreference is incorrectly used to access the success callback. When the application's memory usage increases or if the device's memory is limited, this reference get Garbage-Collected and callback is never called.

    opened by DavisDevasia 0
  • QnD basic auth support by parsing the username and password from the URL

    QnD basic auth support by parsing the username and password from the URL

    This is basically "programming by copy-pasting from stackoverflow" since I don't really do Java but I wanted to test the demo app and I sure as heck did not want to leave the logstash instance completely open for anyone to push any crap into our ELK.

    opened by rambo 0
  • Not found on mavenCentral()?

    Not found on mavenCentral()?

    I've added mavenCentral for other libraries since jcenter is sunsetting, but this is the only library that isn't resolving.

    Can you verify the latest version is distributed?

    opened by emitchel 7
  • expiryTime not change

    expiryTime not change

    Hi! I am using this library and it works fine but when I change the expiry period of logs in this way, it is not working:

    HyperLog.initialize(Constants.appContext, 172800, new CustomLogMessageFormat(this)); // 2 days

    Is there any other change that I have to do?? Thanks in advance!

    opened by aflames 0
  • How to Change Log file name ?

    How to Change Log file name ?

    How to change log file name present its saving as with timestamp format 2019_11_07T06_56_34.128Z.txt. I want to save with different names.

    can anyone suggest??

    opened by NRavva 1
Owner
HyperTrack
Build applications that track the movement of your business
HyperTrack
A logger with a small, extensible API which provides utility on top of Android's normal Log class.

This is a logger with a small, extensible API which provides utility on top of Android's normal Log class. I copy this class into all the little apps

Jake Wharton 9.9k Jan 8, 2023
Library that makes debugging, log collection, filtering and analysis easier.

AndroidLogger Android Library that makes debugging, log collection, filtering and analysis easier. Contains 2 modules: Logger: 'com.github.ShiftHackZ.

ShiftHackZ 2 Jul 13, 2022
Napier is a logger library for Kotlin Multiplatform.

Napier is a logger library for Kotlin Multiplatform. It supports for the android, ios, jvm, js. Logs written in common module are displayed on logger

Akira Aratani 457 Jan 7, 2023
FileLogger - a library for saving logs on Files with custom-formatter on background I/O threads, mobile-ready, android compatible,

The FileLogger is a library for saving logs on Files with custom-formatter on background I/O threads, mobile-ready, android compatible, powered by Java Time library for Android.

Abolfazl Abbasi 12 Aug 23, 2022
An OkHttp interceptor which has pretty logger for request and response. +Mock support

LoggingInterceptor - Interceptor for OkHttp3 with pretty logger Usage val client = OkHttpClient.Builder() client.addInterceptor(LoggingInterceptor

ihsan BAL 1.3k Dec 26, 2022
✔️ Simple, pretty and powerful logger for android

Logger Simple, pretty and powerful logger for android Setup Download implementation 'com.orhanobut:logger:2.2.0' Initialize Logger.addLogAdapter(new A

Orhan Obut 13.5k Dec 30, 2022
Timber + Logger Integration. Make Logcat Prettier, show thread information and more.

Pretty Timber Android Logcat Timber + Logger Integration Video Instructions: https://youtu.be/zoS_i8VshCk Code App.kt class App : Application() {

Awesome Dev Notes | Android Dev Notes YouTube 29 Jun 6, 2022
Logger

StreamingAndroidLogger Introduction Convenient logger that adds support to having multiple different loggers and different log levels for each one of

Jan Rabe 46 Nov 29, 2022
Kotlin Multi Platform Logger, for android an ios : Logcat & print

Multiplatform Preferences Use a single object : Logger in your kotlin shared projects to display logs Note you can also use it in your real code on An

Florent CHAMPIGNY 49 Aug 22, 2022
simple Kotlin logging: colorized logs for Kotlin on the JVM

sklog - simple Kotlin logging Kotlin (JVM) logging library for printing colorized text to the console, with an easy upgrade path to the popular kotlin

null 1 Jul 26, 2022
Yakl - Yet Another Kotlin Logger

YAKL Yet Another Kotlin Logger. Motivation Current jvm loggers have some disadva

Mark Kosichkin 4 Jan 19, 2022
Jambo is an open source remote logging library

Jambo Jambo is an open source remote logging library. For those who would like to see their logs remotely on their android device Jambo is the library

Tabasumu 6 Aug 26, 2022
Kermit is a Kotlin Multiplatform logging utility with composable log outputs

Kermit is a Kotlin Multiplatform logging utility with composable log outputs. The library provides prebuilt loggers for outputting to platform logging tools such as Logcat and NSLog.

Touchlab 395 Jan 4, 2023
Kotlin multi-platform logging library with structured logging and coroutines support

Klogging Klogging is a pure-Kotlin logging library that aims to be flexible and easy to use. It uses Kotlin idioms for creating loggers and sending lo

Klogging 51 Dec 20, 2022
Gadget is a library that makes analytics tracking easier for android apps

gadget (In RC Stage) Gadget is a library that makes analytics tracking easier for android apps.

Taylan Sabırcan 54 Nov 29, 2022
This is an Kotlin Library that enables Annotation-triggered method call logging for Kotlin Multiplatform.

This is an Kotlin Library that enables Annotation-triggered method call logging for Kotlin Multiplatform.

Jens Klingenberg 187 Dec 18, 2022
An in-display logging library for Android 📲

Vlog provides an easy and convenient way to access logs right on your phone.

girish budhwani 121 Dec 26, 2022
📄The reliable, generic, fast and flexible logging framework for Android

logback-android v2.0.0 Overview logback-android brings the power of logback to Android. This library provides a highly configurable logging framework

Tony Trinh 1.1k Jan 5, 2023
Simple application to log your mood through the day and explain feature flags.

Mood Logger App (Android version) This Repo This repository contains code for building a very basic application to log your mood through the days. The

MongoDB Developer Relations 3 Oct 24, 2021