Stream android logcat output to an sd card

落花浮王杯 提交于 2019-12-18 05:00:14

问题


I want to achieve the following but so far, no luck

  • Open a file in the SD Card when the android application first started.
  • Stream the logcat output to the file.
  • When the application exits, stop the logcat streaming.

In my ApplicationClass extends Application onCreate() method, I do this

wwLogManager.openLogFile();

and here's the code in the openLogFile()

        private static final String LOGCAT_COMMAND = "logcat -v time -f ";
        String timestamp = Long.toString(System.currentTimeMillis());
        String logFileName = BuildConstants.LOG_LOCATION + "_" + timestamp + ".log";                    
        mLogFile = new File(Environment.getExternalStorageDirectory() + logFileName);
        mLogFile.createNewFile();
        String cmd = LOGCAT_COMMAND + mLogFile.getAbsolutePath();
        Runtime.getRuntime().exec(cmd);

I do get log files in the sd card, but the log output in these files do not have any trace of the Log.i() calls that I placed in my activities. Is the logcat command that I used here correct? Thanks!


回答1:


I apologize if I am misunderstanding your goals, but perhaps you could use the java.util.logging API instead of using Logcat or the Android Logging mechanism.

Like the Android logging API, the java.util.logging API allows you to easily log messages at various levels, such as FINE, FINER, WARN, SEVERE, etc.

But the standard logging API has additional advantages, too. For example, you can easily create a log file by using a FileHandler. In fact, FileHandler has a built-in log rotation mechanism, so you don't have to worry (so much) about cleaning up the log files. You can also create a hierarchy of Loggers; so, for example, if you have two Loggers, com.example.foo and com.example.foo.bar, changing the logging level of the former will also change the logging level of the latter. This will even work if the two Loggers are created in different classes! Moreover, you change logging behavior at runtime by specifying a logging configuration file. Finally, you can customize the format of the log by implementing your own Formatter (or just use the SimpleFormatter to avoid the default XML format).

To use the standard logging API, you might try something like this:

    // Logger logger is an instance variable
    // FileHandler logHandler is an instance variable

    try {
        String logDirectory =
            Environment.getExternalStorageDirectory() + "/log_directory";

        // the %g is the number of the current log in the rotation
        String logFileName = logDirectory + "/logfile_base_name_%g.log";

        // ...
        // make sure that the log directory exists, or the next command will fail
        // 

        // create a log file at the specified location that is capped 100kB.  Keep up to 5 logs.
        logHandler = new FileHandler(logFileName, 100 * 1024, 5);
        // use a text-based format instead of the default XML-based format
        logHandler.setFormatter(new SimpleFormatter());
        // get the actual Logger
        logger = Logger.getLogger("com.example.foo");
        // Log to the file by associating the FileHandler with the log
        logger.addHandler(logHandler);
    }
    catch (IOException ioe) {
        // do something wise
    }

    // examples of using the logger
    logger.finest("This message is only logged at the finest level (lowest/most-verbose level)");
    logger.config("This is an config-level message (middle level)");
    logger.severe("This is a severe-level message (highest/least-verbose level)");

The Android logging mechanism is certainly easy and convenient. It isn't very customizable, though, and log filtering must be done with tags, which can easily become unwieldy. By using the java.uitl.logging API, you can avoid dealing with a multitude of tags, yet easily limit the log file to specific parts of your application, gain greater control over the location and appearance of the log, and even customize logging behavior at runtime.




回答2:


I repost my answer here so @JPM and others can see... The code basically just execute the logcat command and then build the log from the input stream.

final StringBuilder log = new StringBuilder();
try {        
    ArrayList<String> commandLine = new ArrayList<String>();
    commandLine.add("logcat");
    commandLine.add("-d");
    ArrayList<String> arguments = ((params != null) && (params.length > 0)) ? params[0] : null;
    if (null != arguments){
        commandLine.addAll(arguments);
    }

    Process process = Runtime.getRuntime().exec(commandLine.toArray(new String[0]));
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

    String line;
    while ((line = bufferedReader.readLine()) != null){ 
        log.append(line);
        log.append(LINE_SEPARATOR); 
    }
} 
catch (IOException e){
        //
} 

return log;



回答3:


Try manually setting a filter as described here: http://developer.android.com/guide/developing/debugging/debugging-log.html#filteringOutput

Something like:

logcat ActivityManager:I MyApp:V *:S

If you replace "MyApp" with the log tags that you are using, that should show you all info (and greater) logs from ActivityManager, and all verbose (and greater) logs from your app.




回答4:


I know this is a late answer to the question but I would highly recommend using Logback to write messages to a log file as well as the logcat.

  1. Copy logback-android-1.0.10-2.jar and slf4j-api-1.7.5.jar to your libs folder.
  2. Right-Click on both libs and from the menu select Build Path -> Add to Build Path.
  3. Create a logback.xml file in your assets folder and enter the following:


  

  
  
    
      %msg
    
  

  
  
    
      WARN
    

    ${LOG_DIR}/log.txt

    
      %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
      
  

  
  
    
    
  
  1. To write a log:

    public class MyActivity extends Activity { public static final Logger logger = LoggerFactory.getLogger(MyActivity.class);

    protected void onCreate(Bundle b)
    {
        super(b);
        try{
            throw new Exception("Test");
        }catch(Exception e){
            logger.error("Something bad happened",e);
        }
    }
    

    }



来源:https://stackoverflow.com/questions/6970169/stream-android-logcat-output-to-an-sd-card

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!