xref: /aosp_15_r20/external/cronet/base/fuchsia/scoped_fx_logger.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2020 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_FUCHSIA_SCOPED_FX_LOGGER_H_
6 #define BASE_FUCHSIA_SCOPED_FX_LOGGER_H_
7 
8 #include <fidl/fuchsia.logger/cpp/fidl.h>
9 #include <lib/syslog/structured_backend/cpp/fuchsia_syslog.h>
10 #include <lib/zx/socket.h>
11 #include <stdint.h>
12 
13 #include <string>
14 #include <string_view>
15 #include <vector>
16 
17 #include "base/base_export.h"
18 
19 namespace base {
20 
21 // Emits log lines to a logger created via the specified LogSink.
22 // This class is thread-safe.
23 class BASE_EXPORT ScopedFxLogger {
24  public:
25   ScopedFxLogger();
26   ~ScopedFxLogger();
27 
28   ScopedFxLogger(ScopedFxLogger&& other);
29   ScopedFxLogger& operator=(ScopedFxLogger&& other);
30 
31   // Returns an instance connected to the process' incoming LogSink service.
32   // The returned instance has a single tag attributing the calling process in
33   // some way (e.g. by Component or process name).
34   // Additional tags may optionally be specified via `tags`.
35   static ScopedFxLogger CreateForProcess(
36       std::vector<std::string_view> tags = {});
37 
38   // Returns an instance connected to the specified LogSink.
39   static ScopedFxLogger CreateFromLogSink(
40       fidl::ClientEnd<fuchsia_logger::LogSink> client_end,
41       std::vector<std::string_view> tags = {});
42 
43   void LogMessage(std::string_view file,
44                   uint32_t line_number,
45                   std::string_view msg,
46                   FuchsiaLogSeverity severity);
47 
is_valid()48   bool is_valid() const { return socket_.is_valid(); }
49 
50  private:
51   ScopedFxLogger(std::vector<std::string_view> tags, zx::socket socket);
52 
53   // For thread-safety these members should be treated as read-only.
54   // They are non-const only to allow move-assignment of ScopedFxLogger.
55   std::vector<std::string> tags_;
56   zx::socket socket_;
57 };
58 
59 }  // namespace base
60 
61 #endif  // BASE_FUCHSIA_SCOPED_FX_LOGGER_H_
62