1/*
2 * Copyright (C) 2011 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.support.v4.util;
18
19import android.util.Log;
20
21import java.io.Writer;
22
23/**
24 * Helper for accessing features in {@link android.util.LogWriter}
25 * introduced after API level 4 in a backwards compatible fashion.
26 *
27 * @hide
28 */
29public class LogWriter extends Writer {
30    private final String mTag;
31    private StringBuilder mBuilder = new StringBuilder(128);
32
33    /**
34     * Create a new Writer that sends to the log with the given priority
35     * and tag.
36     *
37     * @param tag A string tag to associate with each printed log statement.
38     */
39    public LogWriter(String tag) {
40        mTag = tag;
41    }
42
43    @Override public void close() {
44        flushBuilder();
45    }
46
47    @Override public void flush() {
48        flushBuilder();
49    }
50
51    @Override public void write(char[] buf, int offset, int count) {
52        for(int i = 0; i < count; i++) {
53            char c = buf[offset + i];
54            if ( c == '\n') {
55                flushBuilder();
56            }
57            else {
58                mBuilder.append(c);
59            }
60        }
61    }
62
63    private void flushBuilder() {
64        if (mBuilder.length() > 0) {
65            Log.d(mTag, mBuilder.toString());
66            mBuilder.delete(0, mBuilder.length());
67        }
68    }
69}
70