blob: f53af1a12611dae85b6fad4366d034321de18abe [file] [log] [blame]
Craig Mautner02d3c982013-11-05 14:34:06 -08001/*
2 * Copyright (C) 2013 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 com.android.server;
18
19import android.text.format.DateFormat;
20
21import java.io.PrintWriter;
22
23public class CircularLog {
24 private final String[] mLog;
25 int mHead;
26
27 public CircularLog(int size) {
28 mLog = new String[size];
29 mLog[mHead++] = "Log start, less than " + size + " log entries entered.";
30 }
31
32 public void add(String msg) {
33 StringBuffer sb = new StringBuffer();
34 long now = System.currentTimeMillis();
35 sb.append(DateFormat.format("yyyy-MM-dd HH:mm:ss", now));
36 sb.append(".");
37 sb.append(String.format("%03d: ", now % 1000));
38 sb.append(msg);
39
40 mLog[(int)(mHead % mLog.length)] = sb.toString();
41 ++mHead;
42 }
43
44 public String[] getLog() {
45 final int length = Math.min(mHead, mLog.length);
46 final String[] logCopy = new String[length];
47 if (mHead > length) {
48 final int start = mHead % length;
49 System.arraycopy(mLog, start, logCopy, 0, length - start);
50 System.arraycopy(mLog, 0, logCopy, length - start, start);
51 } else {
52 System.arraycopy(mLog, 0, logCopy, 0, length);
53 }
54 return logCopy;
55 }
56
57 public void dump(PrintWriter pw, String prefix) {
58 final int length = Math.min(mHead, mLog.length);
59 if (mHead > length) {
60 final int start = mHead % length;
61 for (int i = start; i < length; ++i) {
62 pw.print(prefix); pw.println(mLog[i]);
63 }
64 for (int i = 0; i < start; ++i) {
65 pw.print(prefix); pw.println(mLog[i]);
66 }
67 } else {
68 for (int i = 0; i < length; ++i) {
69 pw.print(prefix); pw.println(mLog[i]);
70 }
71 }
72 }
73}