1 /*
2 * Copyright (C) 2017 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 #include "log.h"
18
19 #ifndef ANDROID
20 #include <stdarg.h>
21 #ifdef USE_LOG_TIMESTAMPS
22 #include <time.h>
23 #endif // USE_LOG_TIMESTAMPS
24
vlogf(FILE * stream,const char * fmt,va_list args)25 static void vlogf(FILE* stream, const char* fmt, va_list args) {
26 #ifdef USE_LOG_TIMESTAMPS
27 struct timespec ts;
28 struct tm localTime;
29 static bool newLine = true;
30 if (newLine && clock_gettime(CLOCK_REALTIME, &ts) == 0) {
31 time_t now = ts.tv_sec;
32 if (localtime_r(&now, &localTime)) {
33 char format[32];
34 char timestamp[1024];
35 snprintf(format, sizeof(format), "[%%T.%03lld] ", (long long)(ts.tv_nsec) / 1000000);
36 strftime(timestamp, sizeof(timestamp), format, &localTime);
37 fprintf(stream, "%s ", timestamp);
38 }
39 }
40 newLine = (fmt[strlen(fmt) - 1] == '\n');
41 #endif // USE_LOG_TIMESTAMPS
42 vfprintf(stream, fmt, args);
43 }
44
logf(FILE * stream,const char * fmt,...)45 static void logf(FILE* stream, const char* fmt, ...) {
46 va_list args;
47 va_start(args, fmt);
48 vlogf(stream, fmt, args);
49 va_end(args);
50 }
51
loge(const char * fmt,...)52 void loge(const char* fmt, ...) {
53 va_list args;
54 va_start(args, fmt);
55 vlogf(stderr, fmt, args);
56 va_end(args);
57 }
58
logd(const char * fmt,...)59 void logd(const char* fmt, ...) {
60 va_list args;
61 va_start(args, fmt);
62 vlogf(stdout, fmt, args);
63 va_end(args);
64 }
65 #endif // !ANDROID
66