1 // 2 // Copyright (C) 2022 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 #pragma once 17 18 #include <shared_mutex> 19 #include <thread> 20 #include <unordered_map> 21 22 #include <android-base/logging.h> 23 #include <fruit/fruit.h> 24 25 #include "common/libs/fs/shared_fd.h" 26 27 namespace cuttlefish { 28 29 /** Per-thread logging state manager class. */ 30 class ServerLogger { 31 public: 32 /** 33 * Thread-specific logger instance. 34 * 35 * When a `LOG(severity)` message is written on the same thread where this 36 * object was created, the message will be sent to the file descriptor stored 37 * in this object. 38 */ 39 class ScopedLogger { 40 public: 41 friend ServerLogger; 42 43 ScopedLogger(ScopedLogger&&) noexcept; 44 ~ScopedLogger(); 45 46 private: 47 ScopedLogger(ServerLogger&, SharedFD target); 48 49 /** Callback for `LOG(severity)` messages */ 50 void LogMessage(android::base::LogId log_buffer_id, 51 android::base::LogSeverity severity, const char* tag, 52 const char* file, unsigned int line, const char* message); 53 54 ServerLogger& server_logger_; 55 SharedFD target_; 56 }; 57 INJECT(ServerLogger()); 58 ~ServerLogger(); 59 60 /** 61 * Configure `LOG(severity)` messages to write to the given file descriptor 62 * for the lifetime of the returned object. 63 */ 64 ScopedLogger LogThreadToFd(SharedFD); 65 66 private: 67 std::shared_mutex thread_loggers_lock_; 68 std::unordered_map<std::thread::id, ScopedLogger*> thread_loggers_; 69 }; 70 71 } // namespace cuttlefish 72