Android-cuttlefish cvd tool
logging_splitters.h
Go to the documentation of this file.
1/*
2 * Copyright (C) 2020 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#pragma once
18
19#include <inttypes.h>
20#include <string.h>
21#include <time.h>
22#include <vector>
23
26
27#define LOGGER_ENTRY_MAX_PAYLOAD 4068 // This constant is not in the NDK.
28
29namespace android {
30namespace base {
31
32// This splits the message up line by line, by calling log_function with a pointer to the start of
33// each line and the size up to the newline character. It sends size = -1 for the final line.
34template <typename F, typename... Args>
35static void SplitByLines(const char* msg, const F& log_function, Args&&... args) {
36 const char* newline = strchr(msg, '\n');
37 while (newline != nullptr) {
38 log_function(msg, newline - msg, args...);
39 msg = newline + 1;
40 newline = strchr(msg, '\n');
41 }
42
43 log_function(msg, -1, args...);
44}
45
46// This splits the message up into chunks that logs can process delimited by new lines. It calls
47// log_function with the exact null terminated message that should be sent to logd.
48// Note, despite the loops and snprintf's, if severity is not fatal and there are no new lines,
49// this function simply calls log_function with msg without any extra overhead.
50template <typename F>
51static void SplitByLogdChunks(LogId log_id, LogSeverity severity, const char* tag, const char* file,
52 unsigned int line, const char* msg, const F& log_function) {
53 // The maximum size of a payload, after the log header that logd will accept is
54 // LOGGER_ENTRY_MAX_PAYLOAD, so subtract the other elements in the payload to find the size of
55 // the string that we can log in each pass.
56 // The protocol is documented in liblog/README.protocol.md.
57 // Specifically we subtract a byte for the priority, the length of the tag + its null terminator,
58 // and an additional byte for the null terminator on the payload. We subtract an additional 32
59 // bytes for slack, similar to java/android/util/Log.java.
60 ptrdiff_t max_size = LOGGER_ENTRY_MAX_PAYLOAD - strlen(tag) - 35;
61 if (max_size <= 0) {
62 abort();
63 }
64 // If we're logging a fatal message, we'll append the file and line numbers.
65 bool add_file = file != nullptr && (severity == FATAL || severity == FATAL_WITHOUT_ABORT);
66
67 std::string file_header;
68 if (add_file) {
69 file_header = StringPrintf("%s:%u] ", file, line);
70 }
71 int file_header_size = file_header.size();
72
73 __attribute__((uninitialized)) std::vector<char> logd_chunk(max_size + 1);
74 ptrdiff_t chunk_position = 0;
75
76 auto call_log_function = [&]() {
77 log_function(log_id, severity, tag, logd_chunk.data());
78 chunk_position = 0;
79 };
80
81 auto write_to_logd_chunk = [&](const char* message, int length) {
82 int size_written = 0;
83 const char* new_line = chunk_position > 0 ? "\n" : "";
84 if (add_file) {
85 size_written = snprintf(logd_chunk.data() + chunk_position, logd_chunk.size() - chunk_position,
86 "%s%s%.*s", new_line, file_header.c_str(), length, message);
87 } else {
88 size_written = snprintf(logd_chunk.data() + chunk_position, logd_chunk.size() - chunk_position,
89 "%s%.*s", new_line, length, message);
90 }
91
92 // This should never fail, if it does and we set size_written to 0, which will skip this line
93 // and move to the next one.
94 if (size_written < 0) {
95 size_written = 0;
96 }
97 chunk_position += size_written;
98 };
99
100 const char* newline = strchr(msg, '\n');
101 while (newline != nullptr) {
102 // If we have data in the buffer and this next line doesn't fit, write the buffer.
103 if (chunk_position != 0 && chunk_position + (newline - msg) + 1 + file_header_size > max_size) {
104 call_log_function();
105 }
106
107 // Otherwise, either the next line fits or we have any empty buffer and too large of a line to
108 // ever fit, in both cases, we add it to the buffer and continue.
109 write_to_logd_chunk(msg, newline - msg);
110
111 msg = newline + 1;
112 newline = strchr(msg, '\n');
113 }
114
115 // If we have left over data in the buffer and we can fit the rest of msg, add it to the buffer
116 // then write the buffer.
117 if (chunk_position != 0 &&
118 chunk_position + static_cast<int>(strlen(msg)) + 1 + file_header_size <= max_size) {
119 write_to_logd_chunk(msg, -1);
120 call_log_function();
121 } else {
122 // If the buffer is not empty and we can't fit the rest of msg into it, write its contents.
123 if (chunk_position != 0) {
124 call_log_function();
125 }
126 // Then write the rest of the msg.
127 if (add_file) {
128 snprintf(logd_chunk.data(), logd_chunk.size(), "%s%s", file_header.c_str(), msg);
129 log_function(log_id, severity, tag, logd_chunk.data());
130 } else {
131 log_function(log_id, severity, tag, msg);
132 }
133 }
134}
135
136static std::pair<int, int> CountSizeAndNewLines(const char* message) {
137 int size = 0;
138 int new_lines = 0;
139 while (*message != '\0') {
140 size++;
141 if (*message == '\n') {
142 ++new_lines;
143 }
144 ++message;
145 }
146 return {size, new_lines};
147}
148
149// This adds the log header to each line of message and returns it as a string intended to be
150// written to stderr.
151static std::string StderrOutputGenerator(const struct timespec& ts, int pid, uint64_t tid,
152 LogSeverity severity, const char* tag, const char* file,
153 unsigned int line, const char* message) {
154 struct tm now;
155 localtime_r(&ts.tv_sec, &now);
156 char timestamp[sizeof("mm-DD HH:MM:SS.mmm\0")];
157 size_t n = strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
158 snprintf(timestamp + n, sizeof(timestamp) - n, ".%03ld", ts.tv_nsec / (1000 * 1000));
159
160 static const char log_characters[] = "VDIWEFF";
161 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
162 "Mismatch in size of log_characters and values in LogSeverity");
163 char severity_char = log_characters[severity];
164 std::string line_prefix;
165 const char* real_tag = tag ? tag : "nullptr";
166 if (file != nullptr) {
167 line_prefix = StringPrintf("%s %5d %5" PRIu64 " %c %-8s: %s:%u ", timestamp, pid, tid,
168 severity_char, real_tag, file, line);
169 } else {
170 line_prefix =
171 StringPrintf("%s %5d %5" PRIu64 " %c %-8s: ", timestamp, pid, tid, severity_char, real_tag);
172 }
173
174 auto [size, new_lines] = CountSizeAndNewLines(message);
175 std::string output_string;
176 output_string.reserve(size + new_lines * line_prefix.size() + 1);
177
178 auto concat_lines = [&](const char* message, int size) {
179 output_string.append(line_prefix);
180 if (size == -1) {
181 output_string.append(message);
182 } else {
183 output_string.append(message, size);
184 }
185 output_string.append("\n");
186 };
187 SplitByLines(message, concat_lines);
188 return output_string;
189}
190
191} // namespace base
192} // namespace android
log_id
Definition: log.h:138
uint32_t size
Definition: io.h:2
#define LOGGER_ENTRY_MAX_PAYLOAD
Definition: logging_splitters.h:27
#define arraysize(array)
Definition: macros.h:76
static std::pair< int, int > CountSizeAndNewLines(const char *message)
Definition: logging_splitters.h:136
std::string StringPrintf(const char *fmt,...) __attribute__((__format__(__printf__
Definition: stringprintf.cpp:68
static void SplitByLogdChunks(LogId log_id, LogSeverity severity, const char *tag, const char *file, unsigned int line, const char *msg, const F &log_function)
Definition: logging_splitters.h:51
LogId
Definition: logging.h:97
static std::string StderrOutputGenerator(const struct timespec &ts, int pid, uint64_t tid, LogSeverity severity, const char *tag, const char *file, unsigned int line, const char *message)
Definition: logging_splitters.h:151
LogSeverity
Definition: logging.h:87
@ FATAL_WITHOUT_ABORT
Definition: logging.h:93
@ FATAL
Definition: logging.h:94
static void SplitByLines(const char *msg, const F &log_function, Args &&... args)
Definition: logging_splitters.h:35
Definition: map_ptr.h:34
class incremental::File __attribute__
std::vector< std::string_view > Args
Definition: incremental.h:28
double now()
Definition: util.cpp:45