1/* 2 * Copyright (C) 2006 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 17package android.util; 18 19import java.io.FileDescriptor; 20import java.io.PrintWriter; 21import java.util.Calendar; 22import java.util.Iterator; 23import java.util.Deque; 24import java.util.ArrayDeque; 25 26/** 27 * @hide 28 */ 29public final class LocalLog { 30 31 private final Deque<String> mLog; 32 private final int mMaxLines; 33 34 public LocalLog(int maxLines) { 35 mMaxLines = Math.max(0, maxLines); 36 mLog = new ArrayDeque<>(mMaxLines); 37 } 38 39 public void log(String msg) { 40 if (mMaxLines <= 0) { 41 return; 42 } 43 Calendar c = Calendar.getInstance(); 44 c.setTimeInMillis(System.currentTimeMillis()); 45 append(String.format("%tm-%td %tH:%tM:%tS.%tL - %s", c, c, c, c, c, c, msg)); 46 } 47 48 private synchronized void append(String logLine) { 49 while (mLog.size() >= mMaxLines) { 50 mLog.remove(); 51 } 52 mLog.add(logLine); 53 } 54 55 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 56 Iterator<String> itr = mLog.iterator(); 57 while (itr.hasNext()) { 58 pw.println(itr.next()); 59 } 60 } 61 62 public synchronized void reverseDump(FileDescriptor fd, PrintWriter pw, String[] args) { 63 Iterator<String> itr = mLog.descendingIterator(); 64 while (itr.hasNext()) { 65 pw.println(itr.next()); 66 } 67 } 68 69 public static class ReadOnlyLocalLog { 70 private final LocalLog mLog; 71 ReadOnlyLocalLog(LocalLog log) { 72 mLog = log; 73 } 74 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 75 mLog.dump(fd, pw, args); 76 } 77 public void reverseDump(FileDescriptor fd, PrintWriter pw, String[] args) { 78 mLog.reverseDump(fd, pw, args); 79 } 80 } 81 82 public ReadOnlyLocalLog readOnlyLocalLog() { 83 return new ReadOnlyLocalLog(this); 84 } 85} 86