klog.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 <cutils/klog.h>
  17. #include <errno.h>
  18. #include <fcntl.h>
  19. #include <stdarg.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <sys/stat.h>
  24. #include <sys/types.h>
  25. #include <unistd.h>
  26. #include <cutils/android_get_control_file.h>
  27. static int klog_level = KLOG_INFO_LEVEL;
  28. void klog_set_level(int level) {
  29. klog_level = level;
  30. }
  31. static int __open_klog(void) {
  32. static const char kmsg_device[] = "/dev/kmsg";
  33. int ret = android_get_control_file(kmsg_device);
  34. if (ret >= 0) return ret;
  35. return TEMP_FAILURE_RETRY(open(kmsg_device, O_WRONLY | O_CLOEXEC));
  36. }
  37. #define LOG_BUF_MAX 512
  38. void klog_writev(int level, const struct iovec* iov, int iov_count) {
  39. if (level > klog_level) return;
  40. static int klog_fd = __open_klog();
  41. if (klog_fd == -1) return;
  42. TEMP_FAILURE_RETRY(writev(klog_fd, iov, iov_count));
  43. }
  44. void klog_write(int level, const char* fmt, ...) {
  45. if (level > klog_level) return;
  46. char buf[LOG_BUF_MAX];
  47. va_list ap;
  48. va_start(ap, fmt);
  49. vsnprintf(buf, sizeof(buf), fmt, ap);
  50. va_end(ap);
  51. buf[LOG_BUF_MAX - 1] = 0;
  52. struct iovec iov[1];
  53. iov[0].iov_base = buf;
  54. iov[0].iov_len = strlen(buf);
  55. klog_writev(level, iov, 1);
  56. }