• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #ifndef TENSORFLOW_CORE_PLATFORM_LOGGER_H_
17 #define TENSORFLOW_CORE_PLATFORM_LOGGER_H_
18 
19 #include "google/protobuf/any.pb.h"
20 #include "tensorflow/core/platform/protobuf.h"
21 
22 namespace tensorflow {
23 
24 // Abstract logging interface. Contrary to logging.h, this class describes an
25 // interface, not a concrete logging mechanism. This is useful when we want to
26 // log anything to a non-local place, e.g. a database.
27 class Logger {
28  public:
29   // The singleton is supposed to be used in the following steps:
30   // * At program start time, REGISTER_MODULE_INITIALIZER calls
31   //   SetSingletonFactory.
32   // * At some point in the program execution, Singleton() is called for the
33   //   first time, initializing the logger.
34   // * Succeeding calls to Singleton() return the initialized logger.
35   using FactoryFunc = Logger* (*)();
36 
SetSingletonFactory(FactoryFunc factory)37   static void SetSingletonFactory(FactoryFunc factory) {
38     singleton_factory_ = factory;
39   }
40 
41   // Returns the per-process Logger instance, constructing synchronously it if
42   // necessary.
43   static Logger* GetSingleton();
44 
45   // Like GetSingleton, except that this does not wait for the construction of
46   // Logger to finish before returning.
47   //
48   // Returns the constructed instance of Logger if it has been constructed,
49   // otherwise returns nullptr (if the logger is not ready yet).
50   static Logger* GetSingletonAsync();
51 
52   virtual ~Logger() = default;
53 
54   // Logs a typed proto.
55   template <typename ProtoType>
LogProto(const ProtoType & proto)56   void LogProto(const ProtoType& proto) {
57     google::protobuf::Any any;
58     any.PackFrom(proto);
59     DoLogProto(&any);
60   }
61 
62   // Flushes any pending log. Blocks until everything is flushed.
Flush()63   void Flush() { DoFlush(); }
64 
65  private:
66   virtual void DoLogProto(google::protobuf::Any* proto) = 0;
67   virtual void DoFlush() = 0;
68 
69   static FactoryFunc singleton_factory_;
70 
71   friend struct AsyncSingletonImpl;
72 };
73 
74 }  // namespace tensorflow
75 
76 #endif  // TENSORFLOW_CORE_PLATFORM_LOGGER_H_
77