1 /* 2 * Copyright (C) 2021 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.launcher3.model; 17 18 import android.util.Log; 19 20 import androidx.annotation.Nullable; 21 22 import java.util.ArrayList; 23 24 /** 25 * Helper logger that collects logs while {@code LoaderTask#run} executes and prints them all iff 26 * an exception is caught in {@code LoaderTask#run}. 27 */ 28 public class LoaderMemoryLogger { 29 30 private static final String TAG = "LoaderMemoryLogger"; 31 32 private final ArrayList<LogEntry> mLogEntries = new ArrayList<>(); 33 LoaderMemoryLogger()34 protected LoaderMemoryLogger() {} 35 addLog(int logLevel, String tag, String log)36 protected void addLog(int logLevel, String tag, String log) { 37 addLog(logLevel, tag, log, null); 38 } 39 addLog( int logLevel, String tag, String log, Exception stackTrace)40 protected void addLog( 41 int logLevel, String tag, String log, Exception stackTrace) { 42 switch (logLevel) { 43 case Log.ASSERT: 44 case Log.ERROR: 45 case Log.DEBUG: 46 case Log.INFO: 47 case Log.VERBOSE: 48 case Log.WARN: 49 mLogEntries.add(new LogEntry(logLevel, tag, log, stackTrace)); 50 break; 51 default: 52 throw new IllegalArgumentException("Invalid log level provided: " + logLevel); 53 54 } 55 } 56 clearLogs()57 protected void clearLogs() { 58 mLogEntries.clear(); 59 } 60 printLogs()61 protected void printLogs() { 62 for (LogEntry logEntry : mLogEntries) { 63 String tag = String.format("%s: %s", TAG, logEntry.mLogTag); 64 String logString = logEntry.mStackStrace == null 65 ? logEntry.mLogString 66 : String.format( 67 "%s\n%s", 68 logEntry.mLogString, 69 Log.getStackTraceString(logEntry.mStackStrace)); 70 71 Log.println(logEntry.mLogLevel, tag, logString); 72 } 73 clearLogs(); 74 } 75 76 private static class LogEntry { 77 78 protected final int mLogLevel; 79 protected final String mLogTag; 80 protected final String mLogString; 81 @Nullable protected final Exception mStackStrace; 82 LogEntry( int logLevel, String logTag, String logString, @Nullable Exception stackStrace)83 protected LogEntry( 84 int logLevel, String logTag, String logString, @Nullable Exception stackStrace) { 85 mLogLevel = logLevel; 86 mLogTag = logTag; 87 mLogString = logString; 88 mStackStrace = stackStrace; 89 } 90 } 91 } 92