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