Dima Zavin | 8f91282 | 2011-08-31 18:26:17 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2008 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 <sys/stat.h> |
| 18 | #include <sys/types.h> |
| 19 | #include <fcntl.h> |
| 20 | #include <stdarg.h> |
| 21 | #include <stdio.h> |
| 22 | #include <stdlib.h> |
| 23 | #include <string.h> |
| 24 | #include <unistd.h> |
| 25 | |
| 26 | #include <cutils/klog.h> |
| 27 | |
| 28 | static int klog_fd = -1; |
| 29 | static int klog_level = KLOG_DEFAULT_LEVEL; |
| 30 | |
| 31 | void klog_set_level(int level) { |
| 32 | klog_level = level; |
| 33 | } |
| 34 | |
| 35 | void klog_init(void) |
| 36 | { |
| 37 | static const char *name = "/dev/__kmsg__"; |
Ken Sumrall | 7425fd1 | 2013-04-03 13:43:11 -0700 | [diff] [blame] | 38 | |
| 39 | if (klog_fd >= 0) return; /* Already initialized */ |
| 40 | |
Dima Zavin | 8f91282 | 2011-08-31 18:26:17 -0700 | [diff] [blame] | 41 | if (mknod(name, S_IFCHR | 0600, (1 << 8) | 11) == 0) { |
| 42 | klog_fd = open(name, O_WRONLY); |
Todd Poynor | 451a6ba | 2013-04-19 12:48:19 -0700 | [diff] [blame] | 43 | if (klog_fd < 0) |
| 44 | return; |
Dima Zavin | 8f91282 | 2011-08-31 18:26:17 -0700 | [diff] [blame] | 45 | fcntl(klog_fd, F_SETFD, FD_CLOEXEC); |
| 46 | unlink(name); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | #define LOG_BUF_MAX 512 |
| 51 | |
| 52 | void klog_write(int level, const char *fmt, ...) |
| 53 | { |
| 54 | char buf[LOG_BUF_MAX]; |
| 55 | va_list ap; |
| 56 | |
| 57 | if (level > klog_level) return; |
Ken Sumrall | 7425fd1 | 2013-04-03 13:43:11 -0700 | [diff] [blame] | 58 | if (klog_fd < 0) klog_init(); |
Todd Poynor | 451a6ba | 2013-04-19 12:48:19 -0700 | [diff] [blame] | 59 | if (klog_fd < 0) return; |
Dima Zavin | 8f91282 | 2011-08-31 18:26:17 -0700 | [diff] [blame] | 60 | |
| 61 | va_start(ap, fmt); |
| 62 | vsnprintf(buf, LOG_BUF_MAX, fmt, ap); |
| 63 | buf[LOG_BUF_MAX - 1] = 0; |
| 64 | va_end(ap); |
| 65 | write(klog_fd, buf, strlen(buf)); |
| 66 | } |