• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2021 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 "gd/os/syslog.h"
18 
19 #include <syslog.h>
20 
21 #include <cstdarg>
22 #include <memory>
23 
24 namespace {
25 #define SYSLOG_IDENT "btadapterd"
26 
27 const char kSyslogIdent[] = SYSLOG_IDENT;
28 
29 // Map LOG_TAG_* to syslog mappings
30 const int kTagMap[] = {
31     /*LOG_TAG_VERBOSE=*/LOG_DEBUG,
32     /*LOG_TAG_DEBUG=*/LOG_DEBUG,
33     /*LOG_TAG_INFO=*/LOG_INFO,
34     /*LOG_TAG_WARN=*/LOG_WARNING,
35     /*LOG_TAG_ERROR=*/LOG_ERR,
36     /*LOG_TAG_FATAL=*/LOG_CRIT,
37 };
38 
39 static_assert(sizeof(kTagMap) / sizeof(kTagMap[0]) == LOG_TAG_FATAL + 1);
40 
41 class SyslogWrapper {
42  public:
SyslogWrapper()43   SyslogWrapper() {
44     openlog(kSyslogIdent, LOG_CONS | LOG_NDELAY | LOG_PID | LOG_PERROR, LOG_DAEMON);
45   }
46 
~SyslogWrapper()47   ~SyslogWrapper() {
48     closelog();
49   }
50 };
51 
52 std::unique_ptr<SyslogWrapper> gSyslog;
53 }  // namespace
54 
write_syslog(int tag,const char * format,...)55 void write_syslog(int tag, const char* format, ...) {
56   if (!gSyslog) {
57     gSyslog = std::make_unique<SyslogWrapper>();
58   }
59 
60   // I don't expect to see incorrect tags but making the check anyway so we
61   // don't go out of bounds in the array above.
62   tag = tag <= LOG_TAG_FATAL ? tag : LOG_TAG_ERROR;
63   int level = kTagMap[tag];
64 
65   va_list args;
66   va_start(args, format);
67   vsyslog(level, format, args);
68   va_end(args);
69 }
70