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 
17 package android.util;
18 
19 import android.compat.annotation.UnsupportedAppUsage;
20 import android.os.Build;
21 
22 import java.io.Writer;
23 
24 /** @hide */
25 public class LogWriter extends Writer {
26     private final int mPriority;
27     private final String mTag;
28     private final int mBuffer;
29     private StringBuilder mBuilder = new StringBuilder(128);
30 
31     /**
32      * Create a new Writer that sends to the log with the given priority
33      * and tag.
34      *
35      * @param priority The desired log priority:
36      * {@link android.util.Log#VERBOSE Log.VERBOSE},
37      * {@link android.util.Log#DEBUG Log.DEBUG},
38      * {@link android.util.Log#INFO Log.INFO},
39      * {@link android.util.Log#WARN Log.WARN}, or
40      * {@link android.util.Log#ERROR Log.ERROR}.
41      * @param tag A string tag to associate with each printed log statement.
42      */
43     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
LogWriter(int priority, String tag)44     public LogWriter(int priority, String tag) {
45         mPriority = priority;
46         mTag = tag;
47         mBuffer = Log.LOG_ID_MAIN;
48     }
49 
50     /**
51      * @hide
52      * Same as above, but buffer is one of the LOG_ID_ constants from android.util.Log.
53      */
LogWriter(int priority, String tag, int buffer)54     public LogWriter(int priority, String tag, int buffer) {
55         mPriority = priority;
56         mTag = tag;
57         mBuffer = buffer;
58     }
59 
close()60     @Override public void close() {
61         flushBuilder();
62     }
63 
flush()64     @Override public void flush() {
65         flushBuilder();
66     }
67 
write(char[] buf, int offset, int count)68     @Override public void write(char[] buf, int offset, int count) {
69         for(int i = 0; i < count; i++) {
70             char c = buf[offset + i];
71             if ( c == '\n') {
72                 flushBuilder();
73             }
74             else {
75                 mBuilder.append(c);
76             }
77         }
78     }
79 
flushBuilder()80     private void flushBuilder() {
81         if (mBuilder.length() > 0) {
82             Log.println_native(mBuffer, mPriority, mTag, mBuilder.toString());
83             mBuilder.delete(0, mBuilder.length());
84         }
85     }
86 }
87