Skip to content

Commit

Permalink
Merge pull request #257 from dronekit/improvement_write_log_to_file
Browse files Browse the repository at this point in the history
Improvement write log to file
  • Loading branch information
m4gr3d committed Sep 7, 2015
2 parents 593e646 + b3dc16e commit e5ebb75
Show file tree
Hide file tree
Showing 8 changed files with 190 additions and 14 deletions.
13 changes: 13 additions & 0 deletions ServiceApp/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ def versionPatch = 4
def versionBuild = 2 //bump for dogfood builds, public betas, etc.
def versionPrefix = "3DR Services v"

//Log levels values
def logLevelVerbose = 2;
def logLevelDebug = 3;
def logLevelInfo = 4;
def logLevelWarn = 5;
def logLevelError = 6;
def logLevelAssert = 7;

android {
compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
Expand All @@ -56,6 +64,10 @@ android {

versionCode computeVersionCode(versionMajor, versionMinor, versionPatch, versionBuild)
versionName generateVersionName(versionPrefix, versionMajor, versionMinor, versionPatch)

//Write logs to file preferences
buildConfigField "boolean", "WRITE_LOG_FILE", "false"
buildConfigField "int", "LOG_FILE_LEVEL", "$logLevelDebug"
}

compileOptions {
Expand Down Expand Up @@ -112,6 +124,7 @@ android {
buildTypes {
debug {
versionNameSuffix generateVersionNameSuffix(versionBuild, "dev")
buildConfigField "boolean", "WRITE_LOG_FILE", "true"
}

beta {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,27 @@
import io.fabric.sdk.android.Fabric;
import timber.log.Timber;

import org.droidplanner.services.android.utils.LogToFileTree;
import org.droidplanner.services.android.utils.analytics.GAUtils;
import org.droidplanner.services.android.utils.file.IO.ExceptionWriter;

public class DroidPlannerServicesApp extends Application {

private LogToFileTree logToFileTree;

@Override
public void onCreate() {
super.onCreate();
Fabric.with(this, new Crashlytics());

if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
if(BuildConfig.WRITE_LOG_FILE){
logToFileTree = new LogToFileTree();
Timber.plant(logToFileTree);
}
else {
Timber.plant(new Timber.DebugTree());
}
}

final ExceptionWriter exceptionWriter = new ExceptionWriter(getApplicationContext());
Expand All @@ -36,4 +45,16 @@ public void uncaughtException(Thread thread, Throwable ex) {
GAUtils.initGATracker(this);
GAUtils.startNewSession(null);
}

public void createFileStartLogging() {
if (logToFileTree != null) {
logToFileTree.createFileStartLogging(getApplicationContext());
}
}

public void closeLogFile() {
if(logToFileTree != null) {
logToFileTree.stopLoggingThread();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import com.o3dr.services.android.lib.model.IApiListener;
import com.o3dr.services.android.lib.model.IDroidPlannerServices;

import org.droidplanner.services.android.DroidPlannerServicesApp;
import org.droidplanner.services.android.core.MAVLink.connection.MavLinkConnection;
import org.droidplanner.services.android.core.MAVLink.connection.MavLinkConnectionListener;
import org.droidplanner.services.android.core.survey.CameraInfo;
Expand Down Expand Up @@ -361,6 +362,10 @@ public IBinder onBind(Intent intent) {
@Override
public void onCreate() {
super.onCreate();

final DroidPlannerServicesApp dpApp = (DroidPlannerServicesApp) getApplication();
dpApp.createFileStartLogging();

Timber.d("Creating 3DR Services.");

final Context context = getApplicationContext();
Expand Down Expand Up @@ -419,6 +424,9 @@ public void onDestroy() {
dpServices.destroy();

stopForeground(true);

final DroidPlannerServicesApp dpApp = (DroidPlannerServicesApp) getApplication();
dpApp.closeLogFile();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -751,8 +751,6 @@ public void onDroneEvent(DroneInterfaces.DroneEventsType event, MavLinkDrone dro
if (!soloComp.isConnected()) {
soloComp.start();
return;
} else{
soloComp.refreshState();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ public void run() {
if (version != null)
controllerVersion.set(version);

updateControllerModeIfPossible();
onVersionsUpdated();
}
};
Expand Down Expand Up @@ -346,7 +347,7 @@ public boolean isLinkConnected() {
}

@Override
public void refreshState(){
public void refreshState() {
Timber.d("Artoo link connected.");

startVideoManager();
Expand All @@ -358,15 +359,11 @@ public void refreshState(){

//Update the tx power compliance
loadCurrentEUTxPowerComplianceMode();

updateControllerModeIfPossible();
}

private void onVersionsUpdated(){
if(linkListener != null && areVersionsSet())
linkListener.onVersionsUpdated();

updateControllerModeIfPossible();
}

private void updateControllerModeIfPossible() {
Expand Down Expand Up @@ -451,7 +448,7 @@ public void updateArtooMode(@SoloControllerMode.ControllerMode final int mode, f
postAsyncTask(new Runnable() {
@Override
public void run() {
Timber.d("Switching controller to mode %n", mode);
Timber.d("Switching controller to mode %d", mode);
try {
final boolean supportControllerMode = doesSupportControllerMode();
final String command = supportControllerMode
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package org.droidplanner.services.android.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import org.droidplanner.services.android.BuildConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

import timber.log.Timber;

/**
* Timber Tree to log specific log levels to a file
*/
public class LogToFileTree extends Timber.DebugTree {
private static final SimpleDateFormat LOG_DATE_FORMAT = new SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US);
private static final SimpleDateFormat FILE_DATE_FORMAT = new SimpleDateFormat("yyyy_MM_dd_HH_mm", Locale.US);

private final LinkedBlockingQueue<String> logQueue = new LinkedBlockingQueue<>();
private PrintStream logOutputFile;
private Thread dequeueThread;
private final AtomicBoolean isRunning = new AtomicBoolean(false);
private final Date date = new Date();

@Override
protected void log(int priority, String tag, String message, Throwable t) {
super.log(priority, tag, message, t);

if (isLoggableToFile(priority)) {
String logOutput = getLogMessage(priority, tag, message);
logQueue.add(logOutput);
}
}

private boolean isLoggableToFile(int priority) {
return priority >= BuildConfig.LOG_FILE_LEVEL;
}

private String getLogMessage(int priority, String tag, String message) {
String priorityShort = getPriorityString(priority);
date.setTime(System.currentTimeMillis());
return String.format("%s %s/%s : %s", LOG_DATE_FORMAT.format(date), priorityShort, tag, message);
}

private String getPriorityString(int priority) {
String priorityString = null;
switch (priority) {
case Log.ASSERT:
priorityString = "ASSERT";
break;
case Log.ERROR:
priorityString = "E";
break;
case Log.WARN:
priorityString = "W";
break;
case Log.INFO:
priorityString = "I";
break;
case Log.DEBUG:
priorityString = "D";
break;
case Log.VERBOSE:
priorityString = "V";
break;
default:
priorityString = "";
break;
}
return priorityString;
}

public void createFileStartLogging(final Context context) {
if (dequeueThread != null && dequeueThread.isAlive()) {
stopLoggingThread();
}

dequeueThread = new Thread(new Runnable() {
public void run() {
PackageInfo pInfo;
String version = "";
try {
pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
Timber.w("Failed to get package info");
}

File rootDir = context.getExternalFilesDir(null);
File dir = new File(rootDir, "/log_cat/");
dir.mkdirs();

String fileName = String.format("%s_%s.log", version, FILE_DATE_FORMAT.format(new Date()));
File logFile = new File(dir, fileName);
try {
logOutputFile = new PrintStream(new FileOutputStream(logFile, true));

while (isRunning.get()) {
try {
String message = logQueue.take();
logOutputFile.println(message);
} catch (InterruptedException e) {
Timber.w("Failed to receive message from logQueue");
}
}

} catch (IOException e) {
Timber.w("Failed to open file");
} finally {
isRunning.set(false);
if (logOutputFile != null) {
logOutputFile.close();
}
}
}
});

isRunning.set(true);
dequeueThread.start();
}

public void stopLoggingThread() {
if (dequeueThread != null) {
isRunning.set(false);
dequeueThread.interrupt();
dequeueThread = null;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ public static String getCameraInfoPath(Context context) {
/**
* Storage folder for stacktraces
*/
public static String getLogCatPath(Context context) {
return getPrivateDataPath(context) + "/log_cat/";
public static String getCrashLogPath(Context context) {
return getPrivateDataPath(context) + "/crash_log/";
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;

Expand Down Expand Up @@ -57,11 +56,11 @@ static public File[] getFileList(String path, FilenameFilter filter) {
}

public static FileOutputStream getExceptionFileStream(Context context) throws FileNotFoundException {
File myDir = new File(DirectoryPath.getLogCatPath(context));
File myDir = new File(DirectoryPath.getCrashLogPath(context));
if (!myDir.exists())
myDir.mkdirs();

File file = new File(myDir, getTimeStamp() + ".txt");
File file = new File(myDir, getTimeStamp() + ".log");
if (file.exists())
file.delete();
return new FileOutputStream(file);
Expand Down

0 comments on commit e5ebb75

Please sign in to comment.