klog.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. #include <sys/stat.h>
  17. #include <sys/types.h>
  18. #include <fcntl.h>
  19. #include <stdarg.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <unistd.h>
  24. #include <cutils/klog.h>
  25. static int klog_fd = -1;
  26. static int klog_level = KLOG_DEFAULT_LEVEL;
  27. void klog_set_level(int level) {
  28. klog_level = level;
  29. }
  30. void klog_init(void)
  31. {
  32. static const char *name = "/dev/__kmsg__";
  33. if (mknod(name, S_IFCHR | 0600, (1 << 8) | 11) == 0) {
  34. klog_fd = open(name, O_WRONLY);
  35. fcntl(klog_fd, F_SETFD, FD_CLOEXEC);
  36. unlink(name);
  37. }
  38. }
  39. #define LOG_BUF_MAX 512
  40. void klog_write(int level, const char *fmt, ...)
  41. {
  42. char buf[LOG_BUF_MAX];
  43. va_list ap;
  44. if (level > klog_level) return;
  45. if (klog_fd < 0) return;
  46. va_start(ap, fmt);
  47. vsnprintf(buf, LOG_BUF_MAX, fmt, ap);
  48. buf[LOG_BUF_MAX - 1] = 0;
  49. va_end(ap);
  50. write(klog_fd, buf, strlen(buf));
  51. }