Home | History | Annotate | Download | only in util
      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 
     17 package android.util;
     18 
     19 import java.io.FileDescriptor;
     20 import java.io.PrintWriter;
     21 import java.util.Calendar;
     22 import java.util.Iterator;
     23 import java.util.LinkedList;
     24 
     25 /**
     26  * @hide
     27  */
     28 public final class LocalLog {
     29 
     30     private LinkedList<String> mLog;
     31     private int mMaxLines;
     32     private long mNow;
     33 
     34     public LocalLog(int maxLines) {
     35         mLog = new LinkedList<String>();
     36         mMaxLines = maxLines;
     37     }
     38 
     39     public synchronized void log(String msg) {
     40         if (mMaxLines > 0) {
     41             mNow = System.currentTimeMillis();
     42             StringBuilder sb = new StringBuilder();
     43             Calendar c = Calendar.getInstance();
     44             c.setTimeInMillis(mNow);
     45             sb.append(String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c));
     46             mLog.add(sb.toString() + " - " + msg);
     47             while (mLog.size() > mMaxLines) mLog.remove();
     48         }
     49     }
     50 
     51     public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
     52         Iterator<String> itr = mLog.listIterator(0);
     53         while (itr.hasNext()) {
     54             pw.println(itr.next());
     55         }
     56     }
     57 
     58     public synchronized void reverseDump(FileDescriptor fd, PrintWriter pw, String[] args) {
     59         for (int i = mLog.size() - 1; i >= 0; i--) {
     60             pw.println(mLog.get(i));
     61         }
     62     }
     63 
     64     public static class ReadOnlyLocalLog {
     65         private final LocalLog mLog;
     66         ReadOnlyLocalLog(LocalLog log) {
     67             mLog = log;
     68         }
     69         public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
     70             mLog.dump(fd, pw, args);
     71         }
     72     }
     73 
     74     public ReadOnlyLocalLog readOnlyLocalLog() {
     75         return new ReadOnlyLocalLog(this);
     76     }
     77 }
     78