1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #ifndef _POSIX_SOURCE
20 #define _POSIX_SOURCE
21 #endif
22
23 #ifndef _GNU_SOURCE
24 #define _GNU_SOURCE
25 #endif
26
27 #include <grpc/support/port_platform.h>
28
29 #ifdef GPR_LINUX_LOG
30
31 #include <grpc/support/alloc.h>
32 #include <grpc/support/log.h>
33 #include <grpc/support/string_util.h>
34 #include <grpc/support/time.h>
35 #include <inttypes.h>
36 #include <stdarg.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include <sys/syscall.h>
40 #include <time.h>
41 #include <unistd.h>
42
gettid(void)43 static long gettid(void) { return syscall(__NR_gettid); }
44
gpr_log(const char * file,int line,gpr_log_severity severity,const char * format,...)45 void gpr_log(const char* file, int line, gpr_log_severity severity,
46 const char* format, ...) {
47 /* Avoid message construction if gpr_log_message won't log */
48 if (gpr_should_log(severity) == 0) {
49 return;
50 }
51 char* message = nullptr;
52 va_list args;
53 va_start(args, format);
54 if (vasprintf(&message, format, args) == -1) {
55 va_end(args);
56 return;
57 }
58 va_end(args);
59 gpr_log_message(file, line, severity, message);
60 /* message has been allocated by vasprintf above, and needs free */
61 free(message);
62 }
63
gpr_default_log(gpr_log_func_args * args)64 void gpr_default_log(gpr_log_func_args* args) {
65 const char* final_slash;
66 char* prefix;
67 const char* display_file;
68 char time_buffer[64];
69 time_t timer;
70 gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
71 struct tm tm;
72 static __thread long tid = 0;
73 if (tid == 0) tid = gettid();
74
75 timer = static_cast<time_t>(now.tv_sec);
76 final_slash = strrchr(args->file, '/');
77 if (final_slash == nullptr)
78 display_file = args->file;
79 else
80 display_file = final_slash + 1;
81
82 if (!localtime_r(&timer, &tm)) {
83 strcpy(time_buffer, "error:localtime");
84 } else if (0 ==
85 strftime(time_buffer, sizeof(time_buffer), "%m%d %H:%M:%S", &tm)) {
86 strcpy(time_buffer, "error:strftime");
87 }
88
89 gpr_asprintf(&prefix, "%s%s.%09" PRId32 " %7ld %s:%d]",
90 gpr_log_severity_string(args->severity), time_buffer,
91 now.tv_nsec, tid, display_file, args->line);
92
93 fprintf(stderr, "%-60s %s\n", prefix, args->message);
94 gpr_free(prefix);
95 }
96
97 #endif /* GPR_LINUX_LOG */
98