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_MOUDLE_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 initiailized logger.
35   using FactoryFunc = Logger* (*)();
36 
SetSingletonFactory(FactoryFunc factory)37   static void SetSingletonFactory(FactoryFunc factory) {
38     singleton_factory_ = factory;
39   }
40 
Singleton()41   static Logger* Singleton() {
42     static Logger* instance = singleton_factory_();
43     return instance;
44   }
45 
46   virtual ~Logger() = default;
47 
48   // Logs a typed proto.
49   template <typename ProtoType>
LogProto(const ProtoType & proto)50   void LogProto(const ProtoType& proto) {
51     google::protobuf::Any any;
52     any.PackFrom(proto);
53     DoLogProto(&any);
54   }
55 
56   // Flushes any pending log. Blocks until everything is flushed.
Flush()57   void Flush() { DoFlush(); }
58 
59  private:
60   virtual void DoLogProto(google::protobuf::Any* proto) = 0;
61   virtual void DoFlush() = 0;
62 
63   static FactoryFunc singleton_factory_;
64 };
65 
66 }  // namespace tensorflow
67 
68 #endif  // TENSORFLOW_CORE_PLATFORM_LOGGER_H_
69