Giter Site home page Giter Site logo

puree-android's Introduction

Puree Build Status Android Arsenal Release

Description

Puree is a log collector which provides the following features:

  • Filtering: Enable to interrupt process before sending log. You can add common params to logs, or the sampling of logs.
  • Buffering: Store logs to buffers and send them later.
  • Batching: Send logs in a single request with PureeBufferedOutput.
  • Retrying: Retry to send logs after backoff time if sending logs fails.

Puree helps you unify your logging infrastructure.

Installation

This is published on jitpack and you can use Puree as:

// build.gradle
buildscript {
    repositories {
        maven { url 'https://jitpack.io' }
    }
    ...
}

// app/build.gradle
dependencies {
    implementation "com.github.cookpad:puree-android:$latestVersion"
}

Usage

Initialize

Configure Puree with PureeConfiguration in Application#onCreate(), which registers pairs of what and where.

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        Puree.initialize(buildConfiguration(this));
    }

    public static PureeConfiguration buildConfiguration(Context context) {
        PureeFilter addEventTimeFilter = new AddEventTimeFilter();
        return new PureeConfiguration.Builder(context)
                .pureeSerializer(new PureeGsonSerializer())
                .executor(Executors.newScheduledThreadPool(1)) // optional
                .register(ClickLog.class, new OutLogcat())
                .register(ClickLog.class, new OutBufferedLogcat().withFilters(addEventTimeFilter))
                .build();
    }
}

See also: demo/PureeConfigurator.java

Definition of PureeLog objects

Puree requires that clients supply an implementation of PureeSerializer to be able to serialize the logs. For instance, this is an implementation that uses Gson parser:

public class PureeGsonSerializer implements PureeSerializer {
    private Gson gson = new Gson();

    @Override
    public String serialize(Object object) {
        return gson.toJson(object);
    }
}

A log class is just a POJO whose properties are annotated following the requirements of the Json parser that you provided with PureeSerializer.

public class ClickLog {
    @SerializedName("page")
    private String page;
    @SerializedName("label")
    private String label;

    public ClickLog(String page, String label) {
        this.page = page;
        this.label = label;
    }
}

You can use Puree.send() to send these logs to registered output plugins:

Puree.send(new ClickLog("MainActivity", "Hello"));
// => {"page":"MainActivity","label":"Hello"}

Definition of PureeOutput plugins

There are two types of output plugins: non-buffered and buffered.

  • PureeOutput: Non-buffered output plugins write logs immediately.
  • PureeBufferedOutput: Buffered output plugins enqueue logs to a local storage and then flush them in background tasks.

If you don't need buffering, you can use PureeOutput.

public class OutLogcat extends PureeOutput {
    private static final String TYPE = "out_logcat";

    @Override
    public String type() {
        return TYPE;
    }

    @Override
    public OutputConfiguration configure(OutputConfiguration conf) {
        return conf;
    }

    @Override
    public void emit(String jsonLog) {
        Log.d(TYPE, jsonLog);
    }
}

If you need buffering, you can use PureeBufferedOutput.

public class OutFakeApi extends PureeBufferedOutput {
    private static final String TYPE = "out_fake_api";

    private static final FakeApiClient CLIENT = new FakeApiClient();

    @Override
    public String type() {
        return TYPE;
    }

    @Override
    public OutputConfiguration configure(OutputConfiguration conf) {
        // you can change settings of this plugin
        // set interval of sending logs. defaults to 2 * 60 * 1000 (2 minutes).
        conf.setFlushIntervalMillis(1000);
        // set num of logs per request. defaults to 100.
        conf.setLogsPerRequest(10);
        // set retry count. if fail to send logs, logs will be sending at next time. defaults to 5.
        conf.setMaxRetryCount(3);
        return conf;
    }

    @Override
    public void emit(List<String> jsonLogs, final AsyncResult result) {
        // you have to call result.success or result.fail()
        // to notify whether if puree can clear logs from buffer
        CLIENT.sendLog(jsonLogs, new FakeApiClient.Callback() {
            @Override
            public void success() {
                result.success();
            }

            @Override
            public void fail() {
                result.fail();
            }
        });
    }
}

Definition of Filters

If you need to add common params to each logs, you can use PureeFilter:

public class AddEventTimeFilter implements PureeFilter {
    public JsonObject apply(String jsonLog) {
        JsonObject jsonObject = new JsonParser().parse(jsonLog).getAsJsonObject();
        jsonObject.addProperty("event_time", System.currentTimeMillis());
        return jsonOabject.toString();
    }
}

You can make PureeFilter#apply() to return null to skip sending logs:

public class SamplingFilter implements PureeFilter {
    private final float samplingRate;

    public SamplingFilter(float samplingRate) {
        this.samplingRate = samplingRate;
    }

    @Override
    public JsonObject apply(String jsonLog) {
        return (samplingRate < Math.random() ? null : jsonLog);
    }
}

Then register filters to output plugins on initializing Puree.

new PureeConfiguration.Builder(context)
        .register(ClickLog.class, new OutLogcat())
        .register(ClickLog.class, new OutFakeApi().withFilters(addEventTimeFilter, samplingFilter)
        .build();

Purging old logs

To discard unnecessary recorded logs, purge age can be configured in the PureeBufferedOutput subclass.

public class OutPurge extends PureeBufferedOutput {

    // ..

    @Override
    public OutputConfiguration configure(OutputConfiguration conf) {
        // set to purge buffered logs older than 2 weeks
        conf.setPurgeAgeMillis(2 * 7 * 24 * 60 * 60 * 1000);
        return conf;
    }
}

The configured storage must extend EnhancedPureeStorage to support purging of old logs. The default PureeSQLiteStorage can be used to enable this feature.

new PureeConfiguration.Builder(context)
        .storage(new PureeSQLiteStorage(context))
        .register(ClickLog.class, new OutPurge().withFilters(addEventTimeFilter, samplingFilter)
        .build();

Testing

If you want to mock or ignore Puree.send() and Puree.flush(), you can use Puree.setPureeLogger() to replace the internal logger. See PureeTest.java for details.

Release Engineering

  • Update CHANGES.md
  • git tag $latest_version
  • git push origin $latest_version

See Also

Copyright

Copyright (c) 2014 Cookpad Inc. https://github.com/cookpad

See LICENSE.txt for the license.

puree-android's People

Contributors

astrapi69 avatar chibatching avatar gfx avatar iwaiawi avatar jfsso avatar k4zy avatar keithyokoma avatar litmon avatar mataku avatar nein37 avatar operando avatar rejasupotaro avatar suzukaze avatar tomoima525 avatar victoralbertos avatar zaki50 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

puree-android's Issues

Tasks package's classes are better to extend IntentService

LogHouse Looks good to me:house_with_garden:

I think tasks package's classes are better to extend IntentService, because

  • AsncTask does not correspond to the life cycle of the Fragment and Activity.
  • There is no need to return the results.

How do you think?

Puree artifact jar is empty

4.1.3 is released, but the artifact delivered from maven server is empty, so we can't use any classes and library.
image

Puree v5

Puree v5 I think...

  • Make interface same as Puree-Swift
  • Split sqlite tables between BufferedOutputs for fixing #61
  • (Optional?) Debugging feature
  • (Optional?) Support Kotlin by extension functions

PureeBufferedOutput will never resume, if the flushSync function is skipped by locking storage with another PureeBufferedOutput instance

Hi.

Problem

When there are two or more PureeBufferedOutputs, if the flushSync function is skipped by locking storage with another PureeBufferedOutput instance, it will never resume.

Caused by

  • PureeBufferedOutput has RetryableTaskRunner and send log by the runner.
  • RetryableTaskRunner start by tryToStart function but the function skip if already 'future' exists.
  • PureeBufferedOutput call tryToStart function when receive new log.
  • PureeBufferedOutput#flushSync() will be skipped when 'storage' is locked.
  • RetryableTaskRunner resets 'future' only if it have done the send process (success / failed).
  • So, if there are multiple PureeBufferedOutputs and one locks the 'storage', the other instance's "future" will not be reset and the flushTask will not work. 😵

Idea

I have no idea... 🙀

thanks.

Migrate to Jitpack

Currently, Puree uses Bintray to distribute its artifact on Maven repositories. I'd like to propose moving to Jitpack, because the latter is built on top of Github and does not require us any kind of setup/config/credentials. We only need to create a new tag on Github and that's all. I created this tag https://github.com/cookpad/puree-android/releases/tag/4.1.7 and now the artifact is automatically available by adding implementation 'com.github.cookpad:puree-android:4.1.7' on Gradle.

Should I update the README file to reflect that the new version is on Jitpack or do you guys prefer to keep using Bintray? If you prefer to keep using Bintray, it is better that you keep the ownership of that part and ship the artifact yourself as we don't have experience with Bintray 👍

PureeBufferedOutput not work with SamplingFilter

PureeBufferedOutput#insertSync may be like below?

    @Override
    public void insertSync(String type, JsonObject jsonLog) {
        JsonObject filteredLog = applyFilters(jsonLog);
        if(filteredLog == null) {
            return;
        }
        storage.insert(type, filteredLog);
    }

i want to use the method name `setPurgeAgeMillis` to deal my old data

hi, i want to use the method name setPurgeAgeMillis to deal my old data , but it had been release yet.

is there any plan to release?

simple code like below:

`public class OutPurge extends PureeBufferedOutput {

// ..

@Override
public OutputConfiguration configure(OutputConfiguration conf) {
    // set to purge buffered logs older than 2 weeks
    conf.setPurgeAgeMillis(2 * 7 * 24 * 60 * 60 * 1000);
    return conf;
}

}`

Publishing javadoc

Thanks for your great library guys.

I think publishing javadoc makes the library more understandable.
Actually square's moshi just do it with their gh-pages branch.
How do you think about of it?

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.