xref: /aosp_15_r20/external/executorch/extension/android/jni/log.cpp (revision 523fa7a60841cd1ecfb9cc4201f1ca8b03ed023a)
1 /*
2  * Copyright (c) Meta Platforms, Inc. and affiliates.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree.
7  */
8 
9 #include "log.h"
10 
11 #ifdef __ANDROID__
12 
13 #include <android/log.h>
14 #include <functional>
15 #include <mutex>
16 #include <sstream>
17 
18 using executorch::extension::log_entry;
19 
20 // Number of entries to store in the in-memory log buffer.
21 const size_t log_buffer_length = 16;
22 
23 namespace {
24 std::vector<log_entry> log_buffer_;
25 std::mutex log_buffer_mutex_;
26 } // namespace
27 
28 // For Android, write to logcat
et_pal_emit_log_message(et_timestamp_t timestamp,et_pal_log_level_t level,const char * filename,const char * function,size_t line,const char * message,size_t length)29 void et_pal_emit_log_message(
30     et_timestamp_t timestamp,
31     et_pal_log_level_t level,
32     const char* filename,
33     const char* function,
34     size_t line,
35     const char* message,
36     size_t length) {
37   std::lock_guard<std::mutex> guard(log_buffer_mutex_);
38 
39   while (log_buffer_.size() >= log_buffer_length) {
40     log_buffer_.erase(log_buffer_.begin());
41   }
42 
43   log_buffer_.emplace_back(
44       timestamp, level, filename, function, line, message, length);
45 
46   int android_log_level = ANDROID_LOG_UNKNOWN;
47   if (level == 'D') {
48     android_log_level = ANDROID_LOG_DEBUG;
49   } else if (level == 'I') {
50     android_log_level = ANDROID_LOG_INFO;
51   } else if (level == 'E') {
52     android_log_level = ANDROID_LOG_ERROR;
53   } else if (level == 'F') {
54     android_log_level = ANDROID_LOG_FATAL;
55   }
56 
57   __android_log_print(android_log_level, "ExecuTorch", "%s", message);
58 }
59 
60 namespace executorch::extension {
61 
access_log_buffer(std::function<void (std::vector<log_entry> &)> accessor)62 void access_log_buffer(std::function<void(std::vector<log_entry>&)> accessor) {
63   std::lock_guard<std::mutex> guard(log_buffer_mutex_);
64   accessor(log_buffer_);
65 }
66 
67 } // namespace executorch::extension
68 
69 #endif
70