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 #include <grpc/support/port_platform.h>
20
21 #ifdef GPR_POSIX_LOG
22
23 #include <grpc/support/alloc.h>
24 #include <grpc/support/log.h>
25 #include <grpc/support/time.h>
26 #include <inttypes.h>
27 #include <pthread.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <time.h>
32 #include <string>
33 #include "absl/strings/str_format.h"
34
sys_gettid(void)35 static intptr_t sys_gettid(void) { return (intptr_t)pthread_self(); }
36
gpr_log(const char * file,int line,gpr_log_severity severity,const char * format,...)37 void gpr_log(const char* file, int line, gpr_log_severity severity,
38 const char* format, ...) {
39 /* Avoid message construction if gpr_log_message won't log */
40 if (gpr_should_log(severity) == 0) {
41 return;
42 }
43 char buf[64];
44 char* allocated = nullptr;
45 char* message = nullptr;
46 int ret;
47 va_list args;
48 va_start(args, format);
49 ret = vsnprintf(buf, sizeof(buf), format, args);
50 va_end(args);
51 if (ret < 0) {
52 message = nullptr;
53 } else if ((size_t)ret <= sizeof(buf) - 1) {
54 message = buf;
55 } else {
56 message = allocated = (char*)gpr_malloc((size_t)ret + 1);
57 va_start(args, format);
58 vsnprintf(message, (size_t)(ret + 1), format, args);
59 va_end(args);
60 }
61 gpr_log_message(file, line, severity, message);
62 gpr_free(allocated);
63 }
64
gpr_default_log(gpr_log_func_args * args)65 void gpr_default_log(gpr_log_func_args* args) {
66 const char* final_slash;
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
73 timer = (time_t)now.tv_sec;
74 final_slash = strrchr(args->file, '/');
75 if (final_slash == nullptr)
76 display_file = args->file;
77 else
78 display_file = final_slash + 1;
79
80 if (!localtime_r(&timer, &tm)) {
81 strcpy(time_buffer, "error:localtime");
82 } else if (0 ==
83 strftime(time_buffer, sizeof(time_buffer), "%m%d %H:%M:%S", &tm)) {
84 strcpy(time_buffer, "error:strftime");
85 }
86
87 std::string prefix = absl::StrFormat(
88 "%s%s.%09d %7" PRIdPTR " %s:%d]", gpr_log_severity_string(args->severity),
89 time_buffer, (int)(now.tv_nsec), sys_gettid(), display_file, args->line);
90 fprintf(stderr, "%-70s %s\n", prefix.c_str(), args->message);
91 }
92
93 #endif /* defined(GPR_POSIX_LOG) */
94