You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am prototyping some ways of addressing point 2 (enable/disable based on component, module, class, or source file name) and point 3 (some thread-level awareness and locality). But before I continue, I would like to confirm several things:
glog is an example that shows that point 2 (log filtering by component) is possible, but its current approach of string-matching based on source file names (*.h, *.cc) is not satisfactory for OpenCV, because each module or component in OpenCV may span across many source files.
point 3 (logging and threads) needs clarification. What settings need to be configurable "on per-thread basis"? How to do that globally, given that the main thread might not know the identities of the set of worker threads that will be launched to handle a parallel_for task? I interpret this requirement as providing thread-local configurability for a relevant subset of options.
Regarding the past and future,
What aspects of the current OpenCV logging were found to be major pain points?
What aspects of glog were found to be major pain points?
Should glog be kept or removed?
What aspects of ITT were found to be major pain points?
Should ITT be kept or removed?
OpenCV Core already has basic logging macros. Should these be kept, so as to minimize code changes needed in other modules that use them?
What are the restrictions regarding non-breaking of API if this task is changed to target OpenCV 4.1 instead?
Right now I do not know whether conflicts will exist between these features. Typically, C++ logging frameworks must strike a balance between compile-time control and run-time control. I will post more design documents and code samples when they are ready.
I would like to know what would be proper design versus over-design (over-engineering). It is quite easy to be over-engineering on logging.
IMHO, Tracing / logging should be kept separately.
Tracing is mostly about the performance.
Logging is primary about errors reporting (including crash dumps) and about the current state of application:
missing file, cache
unsupported image codec
optimization branches are enabled/disabled
etc
ITT is just backend for performance tracing. It can be turned off during compilation / in runtime.
The similar things (backends) should be supported for logging:
glog
Android logging (adb logcat)
? Javascript logging (opencv.js)
etc, including OpenCV's simple "stdout" logging should exist too.
OpenCV responsibility here is still "configuration" of logging topics/categories/tags/levels and probably basic formatting.
Logging backends are sinks with own formatting and with/without own filters configuration.
For example, "Network" / out of process sink support should be supported via some logging backend.
We prefer avoid "hard" bind of OpenCV logging API to "glog" only.
But it looks like complicated / over-engineering. So lets start from something that we need to have in OpenCV.
This sample source code is just to illustrate some of the points and functionalities discussed earlier. It is also a learning experience - to know what implementation techniques are valuable, feasible, undesirable, or outright impractical.
I will summarize the lessons learned. Here's an incomplete list:
Each log message attempt should consist of the "metadata" and the "body"
The "metadata" should always be collected, and should be cheap to collect.
The "metadata" alone is used to determine how the message should be filtered.
Of all the parts that make up "metadata", some parts might be unavailable. Logger tries to collect as much as reasonable (cheaply).
Example of "metadata" (incomplete)
Log level
Module name
File, line, function name
Current thread ID (note: could be C++11 thread ID, or OpenCV thread ID)
Example of "optional metadata"
Current class and object pointer, if inside a class or instance method
Information about cv::ParallelLoopBody, if inside a parallelization worker thread
Because of the "optionality" of some metadata, the logging macro needs to be designed with this flexibility in mind, without requiring a large number of macros to cater all combinations.
The log message "body" need not generated if the filtering logic decides to suppress it based on its "metadata".
The stream write operator (operator <<) is a nice way to get around C++ macro expansion issues when a variable number of items need to be passed.
Stream write operator is the code-level item delimiter
Non-lessons:
Although the sample code implements a rudimentary log filtering engine, it might not be necessary. This is an example of over-engineering I mentioned earlier.
The sample code does not implement thread-local control, yet.
The sample code does not implement configurable backend (sink), or simultaneous multiple backend output, yet.
The sample code has not been tested for multi-threading safety.
setLogFilter, getLogFilter and LogFilterFunctionType approach has some issue: filter check function impact can be significant for regular frequent calls (not matter if event logged or it is skipped), including strcmp() calls or regex processing.
Minimal cost effective check may look like this:
if (log_entry_scope.enabled_log_level <= this_message_level)
{
... send log info to sink ...
}
What is "log_entry_scope"?
"c++ static" (global) descriptor of attached log events (except class instances, see below)
initialized only once
all "string" handling or regex processing are performed during this initialization
most part of log descriptors should be initialized "on-demand" to reduce application bootstrap time
all "meta" information is included into descriptor
Main magic here is "scope" configuration. I believe we can re-use tree-based structure.
Example of tree levels:
module: "opencv_imgcodecs"
class(algorithm) / function: "imread"
? sub_functions:
"imread.find_decoder" to dump name of selected decoder
"jpeg_decoder"
? sub events: "cascadeclassifier.no_detections" / "imread.cant_open_file"
...
one LOG_...() macro: with exact file/line/function name
Configured value is:
log level of "filtered" logging scopes: opencv_imgcodecs.imread = DEBUG
Separate large entity of logger is "configurator":
has implementation of "LogFilter" function (setup log level based on metadata)
support runtime reconfiguration of descriptors
should know about all "active" (initialized) logging descriptors to updated them on change requests ("tree" of logging scope should help here)
BTW, "tag" in current macros implementation is placeholder for metadata / "parent" log entry scope:
static LogModule log_module("imgcodecs"); (declared once per module in global scope)
static LogFunction log_function(l_module, "imread"); l_module is a parent scope in configuration tree`
LOG_DEBUG(log_module, "imread() called");
expands to something like this:
// registered and initialized via logging configurator
static LogEntry log_scope_xyz(log_module, __FILE__, __LINE__);
if (log_scope_xyz.log_level <= DEBUG) { ... }
We should have non-global logging descriptors if we want to log events from different class instances separately.
Descriptors are not global "c++ static", they can be stored as class fields.
Q: Should we use other metadata for extra filtering?
The sample code is quite involved, but certain things can be potentially simplified. For example, there is no need for classes ClassDynamicInfo or FunctionDynamicInfo, if the entire "dynamic information" we intend to share (to centrally manage and locally cache) is an int logLevel. We can just store and share a pointer to that integer.
I have just finished writing up the code, haven't got to summarizing the design elements or learned lessons. I will update the Gist with some write-up a few days later, possibly during the weekend.
This sample code could be buggy. I haven't fully conceptualized all of the object lifetime issues. There may be dangling references to expired temporary objects.
I have removed ModuleName etc, choosing to combine the string class functionality into ModuleInfo etc.
The earlier DynamicInfoManager has a subtle "order of static initialization` bug. It is fixed by moving static members into a nested class, and to guarantee its initialization by making it a static local member of a function. (This is the standard practice for resolving this type of bugs.)
I have added a LogLevelManager class. This class is not actually needed; I added it so that I can put four related static (non-member) functions there. These functions are the entry point for getting and setting the log level of anything within the capability of this framework. The functions are:
ConfigLayer is a necessary evil to solve a well-known problematic phenomenon in software configuration - that of clobbering of configs when multiple sources of configs are applied, often applied in a wrong order that's inconsistent with their intended precedence (that a human would expect). I can explain why this design is necessary in maybe 1000 words or so. To put it simply, this is something we can't omit.
With this sample code, I have learned enough about the domain and the requirements so that I can start writing a specification. The specification should be ready by Tuesday.
I also realized that, with the specification I have in mind, this sample code isn't the most efficient implementation. There're lots of rooms for efficiency improvement.
One thing that I have validated through this sample code, is that the overhead of repeated calls to the same function (for example, calling LogLevelManager.Check() using the same FunctionInfo object that's already initialized, can be fast enough that my measured TSC count per repeated call can be as low as 8 - 15. However, the first time initialization (either first-time setting or first-time getting a particular scopes log level cutoff) is quite expensive, with measured TSC count in thousands or tens of thousands, with the current sample code.
I'll now focus on writing the specification, expected to be ready by Tuesday.
Log level indicates the importance (severity and verboseness) of the log message.
The following log levels are defined:
FATAL
ERROR
WARNING
INFO
DEBUG
VERBOSE
Log level is used in two ways:
A log level is specified for each log message.
Log level filtering thresholds are configured so that log messages below a certain importance level are discarded.
Scope-based log filtering
Log messages generated from different parts of the software library / application can have different filtering threshold configured.
These later sections will describe how the logging framework applies different filtering thresholds to logging messages:
Log scope
Configuration layers
Calculation of the effective filtering threshold for a log message
Log scope
Log scope puts log messages into a log message organizational hierarchy.
The following log scopes are defined:
Module
Class (nested under Module)
Function (nested under Class)
The fully qualified name of a log scope is the concatenation of all the names, joined with a period (".").
Example:
Suppose there is a module ModuleOne, a class ClassA nested under ModuleOne, a function FunctionX nested under ClassA.
The fully qualified name of the function's scope is "ModuleOne.ClassA.FunctionX".
Log messages usually have a log scope specified.
If a log message does not have a log scope specified, it is assumed to be at the root scope.
Using log scope for meanings other than module, class, and function
From the logging system's perspective, it is more useful to think of the log scope feature as "Level0.Level1.Level2". The core of the logging system is agnostic to how log scopes are used.
There is a request to have a log scope for "events", which corresponds to cross-cutting concerns that do not fit in the module-class-function hierarchy.
The best approach for handling "events" is yet to be decided, but it is believed that the log scope mechanism should be sufficient.
The only key point is that events must not have name collision with any other things.
(It is not yet decided whether log scopes form a single namespace or a hierarchy of namespaces.)
Configuration layers
There will be at least two configuration layers:
launch-time (shortened to "launch")
runtime
Launch-time configuration is typically loaded from the environment, command-line arguments, configuration file, or hard-coded (for short-term library development needs)
Runtime configuration can be modified at any time.
Background: about the necessity of configuration layers
(Readers already familiar with this concept can skip this section.)
Configuration layer is a mechanism to resolve the issue of configuration clobbering, that is, the overwriting of a set of higher-priority (higher-precedence) configuration data by another set of lower-priority (lower-precedence) configuration data.
While the priority (precedence) of configuration data is a fluid concept determined by application needs, the general existence of multiple sets (or multiple sources) of configuration data with different priority (precedence) should be understood.
A naive implementation which does not incorporate the concept of configuration layers will suffer from this problem, because the priority (precedence) between configuration sets are effectively (de-facto) controlled by the order in which they are loaded (applied).
In large and modular software, or in software consisting of integration of independently-developed and compiled parts, the order in which configuration sets are loaded (applied) are typically poorly-controlled due to mechanisms outside the application user's control.
However, configuration sets can be tagged, from which the priority (precedence) can be determined. This prevents configuration sets from being overwritten against the application user's wish.
Calculation of the effective filtering threshold for a given log message
An earlier example will be reused here to explain the calculation.
Suppose there is a module ModuleOne,
A class ClassA nested under ModuleOne, and
A function FunctionX nested under ClassA.
The fully qualified name of the function's scope is "ModuleOne.ClassA.FunctionX".
Suppose a log message tagged with the function's log scope is to be written.
The cell marked "Checked first (1st)" is to be checked first.
If a filtering threshold is specified within that log scope and configuration layer, it will be used. No other configurations are checked.
Only if a filtering threshold is not specified there, the next one will be checked, and so on.
Table - the order of checking scopes and configuration layers for the effective filtering threshold
if the entire "dynamic information" we intend to share (to centrally manage and locally cache) is an int logLevel
Agree!
Information may be separated into:
global "const" descriptor (module, file name, class name configuration): "static" class member (not changed between class instances)
local dynamic descriptor: "this" or some instance name?
configuration value itself: int logLevel (unique for each class instance)
In this case, configuration manager has "pointers" on these entities:
configuration global/static descriptor
optional "dynamic" descriptor
configured value instance: value
My two last comments are related to wider "OpenCV configuration" issue (there is no such "OE" item).
Logging is a good example / starting point of capturing configuration's problems.
Checked first
Checked second
... Checked last (6th)
I believe this should be simplified.
We store one value for configuration leaf. And we check this value only.
This value is set by:
initialization process: read value from configuration entries or inherit value from the the "parent" category (they pass similar initialization process)
update of configuration parameter: updates all children of updated category. For example, module updates all registered (initialized) nested classes/functions and own class's value (for future initialization of nested unused categories)
(These are links to the buildbot result; links might become broken)
However, based on my experience and opinion, parts of your latest suggestions might be difficult or error-prone to implement. I'll explain below.
Regarding the general questions of "who owns what" and "who has pointers to what", my current design is prepared for the following situations:
Currently, LogManager is the owner of configuration data (consisting of log levels).
There are two valid options for the ownership of the configuration data:
Owned by LogManager, never cleaned up (except during shutdown call or a memory leak detector preparation hook), and observer pointers are given to logging users (classes, objects, functions).
Shared ownership between LogManager and logging users (classes, objects, functions).
The idea of co-locating the configuration data is valid for namespaces (outside-classes), classes and functions. It is not valid for objects, because objects can go away, and LogManager is not notified, resulting in dangling pointers.
The only benefit of co-locating the configuration data with the static LogScope record is memory cache-friendliness.
The overhead of separating them is minor, just one memory pointer (dereference) away. LogScope already caches the pointer to the configuration data block at the first call; see this line of code.
If we want to use co-located configuration data for namespaces, classes and functions because they support static lifetime, then we'll need to manage different kinds of pointers (i.e. having different directions of ownership) in LogManager. The code duplication is significant.
Regarding order of initialization, in particular "when config is loaded" and "when the scope of ModuleOne.ClassA is first entered"
If config is loaded before the static members of ModuleOne.ClassA can be initialized, the LogManager has to parse the config first, but delay the propagation of the data.
Whereas, in my current PR, it does not matter whether the config change comes from initialization or first-time-of-use. It will get a pointer (reference) to the configuration record, and it can read/write directly, without asking LogManager again.
I'm also mindful of the static initialization order fiasco, and I try to consciously make sure my design is compliant, though I may sometimes make some bugs.
Regarding multithreading operations:
Currently, LogManager acquires a mutex for all operations (both getLogThreshold and setLogThreshold). This is a coarse-grained lock.
Opportunity for enhancement: LogManager can use Reader-Writer Lock, or lock-free approaches.
Opportunity for enhancement: LogManager can use a better hash table, because std::unordered_map is slow and requires locking for all (read and write) multi-threaded operations.
The idea of pushing configuration data into logging users require fine-grain locking. However, the number of times of locking and unlocking will increase a lot. It is not clear whether the outcome will be a performance enhancement or regression.
Regarding performance, in particular measurement of execution and memory overheads:
In general, first time initialization is a lot more expensive than repeated use. Much of the "real and necessary work" is done during first time initialization, which is unavoidable.
I would like some outside help defining meaningful benchmark scenarios and performance metrics, from which benchmark test code can be written. I am interested in getting measurement results as well, but I am not certain what scenarios should be tested, and which are truly meaningful to different stakeholders of OpenCV.
I'll continue to explore the boundary of possibilities, to see if there're rooms for enhancement.
Checked first
Checked second
... Checked last (6th)
In practice, it consists of a maximum of three calls to LogManager:
The Function scope will call LogManager to get a pointer (reference) to LogThreshold (code), which is "the configuration data record". The pointer is cached in the Function scope. Here, Checked first and Checked second happens (the two integers are next to each other in the data record). If it says not configured yet (CV_LOG_LEVEL_CHECK_PARENT), ...
The Function scope will call the Class scope, which will call LogManager to get a pointer to its own LogThreshold, if it's the first time.
If it's not found, the Class scope will call the Module scope, which will call LogManager, if it's the first time.
Calls which are not the first time are guaranteed to make zero calls to LogManager. It will go ahead and read from a LogThreshold via a pointer, which is "the configuration data record".
Log context struct which contains category (log level), file (FILE), function (FUNCTION), line (LINE) and version fields.
My proposal
We can slightly tune existing logging facility to add log tags (like in GStreamer), filtering based on tags (like in GStreamer and Android), simple log context (like in Qt) and an interface to override low level logging function (like in FFmpeg and Qt).
I thinke these scopes are too complicated because there can be: namespaces, class inside a class, lambda functions. I don't see how these can be implemented in a reliable way.
I agree that hierarchical log scope can be over-complicated. However, let's not forget that, both wildcard matching and hierarchical log scope searching can be expensive at runtime, if done repeatedly. Any attempt to reduce the amount of work will lead to creation of classes and static objects to cache their results.
But for now, I will present a proof-of-concept design that doesn't do either. Thus, the "tag" must match exactly, as there is no hierarchical setting or wildcard matching.
Line-of-code filtering, i.e. turning on/off logging based on __FILE__, __LINE__, __FUNCTION__ is also expensive at runtime. I haven't found out a good way to make it fast. I'd like to hear suggestions from your team.
I also agree that we should start with the logging macro first (see code) - to envision what the logging macro should look like.
I think we have consensus that the following information will be always captured: log level, tag, file, line, function, time, thread ID.
The "tag" is just a string. However, I think it is appropriate to apply "convention over configuration" thinking here. Why not do this:
Application code pass in the tag name without the string quotes.
The "name" of the tag is implicitly its stringification.
In addition, let's assume that the application code also declares an integer value, whose name has a suffix that is same as the tag.
Example:
(these lines of code can be found in my latest proof-of-concept design, same link as above.)
// we can specify breakfast_time when calling the logging macro.externconstexprint static_logging_level_breakfast_time = 1;
// we can specify dinner_time when calling the logging macro.staticint static_logging_level_dinner_time = 1;
To make this internally-declared integer values configurable centrally, a piece of registration code is needed:
int static_logging_level_your_tag_name = 1;
...
logging_20190125::LogLevelManager::getInstance().registerLogLevel(
"your_tag_name", static_logging_level_your_tag_name);
Regarding thread ID, the least-expensive thread ID that can be computed should be used. Typically, the native thread ID handle is the least-expensive (it is a read from a special location). It is also the case that the native thread ID makes the most sense to programmers.
An approach that avoids the issues of MSVC DLL import/export of variables (as opposed to functions) mentioned in #13836
Throughout this document, unless otherwise specified, any identifiers that contain
the substring "TBD" (short for "to be determined") implies that the actual naming
scheme for these identifiers will be defined at a later time, and through such
future definition it can be guaranteed that accidental name collisions of
identifiers cannot happen.
Example
In the following example, some lines of code are followed by a line of comment
consisting of dots ("."), carets ("^"), and underscores ("_").
The carets indicate the tag that must match exactly in order for the preprocessor macro expansion to work.
The underscores indicate part of the C++ identifier name of the log level variable.
Its name does not have to be the same as the tag (although it is advantageous to be so),
because it is not an input to the preprocessor macro expansion (it is the result of that expansion).
This example uses "leaky_water_pipes" as a fictitious OpenCV module or scope name.
tag: an unqouted string (preprocessor token), to be used in preprocessor operators such as
token pasting, stringification, etc. See Preprocessor Expansion section below.
level: a C++ expression (of enum LogLevel) that evaluates to the log
level of the message.
v: a C++ integer expression that specifies the verbosity sub-level
for all log messages sent at the VERBOSE level. A verbosity sub-level can be
thought of as a fine-grane subdivision of the VERBOSE level. This parameter
must be zero if the log level of the message is not VERBOSE.
msg_args: one or more arguments to the C++ stream insertion operator
that provides input to the formatting of the log message content.
Preprocessor Expansion of the tag argument
The tag argument will be expanded as follows:
Through token-pasting, it should evaluate into the name of a
preprocessor macro with a prescribed prefix. Each use of logging
statement should ensure that the preprocessor macro formed formatting
this token-pasting is actually defined.
Through stringification, it should become the string key value that
allows the log level variable to be manipulated programmatically.
The log level variable
CV_LOGLEVEL_##tag, or CONCAT(CV_LOGLEVEL_, tag)
The result of this expansion shall be another preprocessor macro; this
preprocessor macro can be defined before or after the definition of CV_TBD_LOG.
Usually, CV_TBD_LOG is defined in a header in modules/core/include,
and the CV_LOGLEVEL_tag is defined inside each OpenCV module.
This macro shall evaluate to a C++ expression that yields the log filtering
threshold applicable to that tag. In particular, it is permissible for that
expression to be:
a log level value (a literal value of the LogLevel enum)
the name of a log level variable;
the name of a C++ reference to a log level variable;
a call to a C++ function that returns a log level value;
Each of these choices bring capabilities and limitations. When implementing
logging for each module and scope, the choice should be made after careful
consideration of the specific needs within each module and scope.
Explanation
The prefix "CV_LOGLEVEL_" is pasted together with "diagonstics" to form
"CV_LOGLEVEL_diagnostics". This preprocessor macro needs to have been defined
before the logging statement.
In this example, the actual log level variable only needs to be accessible
within this module or dynamic library ("*.DLL" or "*.so").
Therefore, the variable can be declared extern in a header that is
visible within the module, and then the definition (initialization) can be
placed into one of the compilation units (in exactly one "*.cpp" file).
Allowing programmatic access to log level variable by a string key
A helper class cv::LogLevelRegistration is to be created. Its constructor
method should take a string and a reference (or pointer) to a mutable log level
variable. The constructor should call the LogManager class for the name
and variable to be added to a lookup table (similar to std::unordered_map).
The registration can be scheduled to happen at Deferred dynamic initialization.
However, the relative order between deferred dynamic initialization and other
code is not specified. In other words, it is possible that some code and logging
statements may have been executed while referencing uninitialized log level variables,
or that programmatic access to log level variables by string name may not find
a match because the registration code has not yet executed.
#defineCV_LOG_WITH_META(tag, ...) \
... \
... opencv_log_tag_name_ ## tag ... \
... opencv_log_tag_level_ ## tag ... \
This page (on my Gist) explains why I decided not to use the preprocessor token-pasting technique (the ## operator in preprocessor) to expand tag name into more than one C++ identifiers (tag name and log level).
The basic reason is that token-pasting is incompatible with the use of C++ expressions. Let's say someone enclosed the C++ expression inside a pair of parentheses, as in (expr), and pass it into a C++ preprocessor macro. The token pasting result is then prefix_(expr), which is not the desired result.
For token-pasting and the use of C++ expressions (when calling a C++ preprocessor macro) to co-exist, the C++ expressions need to have no symbols (brackets of any kind, period, ampersand (address-of operator), asterisk (dereference operator), etc) on the left side of the macro's input argument.
However, based on my implementation attempts, I conclude that this is too restrictive. I also concluded that the logging macro needs to be allowed to accept a C++ expression for the "tag" argument. Therefore, preprocessor token-pasting approach cannot be used on the "tag" argument.
As seen in this page (on my Gist) linked above, there are still many ways to use macro expansions that give valid expansion result. Thus, I'm not forbidding the use of all preprocessor techniques; I'm just choosing not to apply token-pasting on the "tag" argument.
C++ expression inside a pair of parentheses, as in (expr)
I believe we should not allow to use custom expressions here.
If someone wants some custom tag, then it should declare its "identifier" above (via additional macro). And then use this identifier - we should have such declarations for each module/file(.cpp)/function/class/method.
Additionally, tag prefix_ implements some compile-time checks to avoid typos or misusing (it is too easy, for example, with "int"-like type of result).
@alalek not only (expr), but &expr will also give bad result. Consider this: user wants to pass in the address of something as tag, and naturally puts & in front of the actual variable.
In other words, token pasting forces us to require logging users to specify the tag in exactly one way: it has to be the suffix of the name of a macro (which needs to be defined by logging user), and CV_LOG will automatically apply the prefix CV_LOGTAG_ ## tag to it and then expand it. The expansion result needs to be a pointer to LogTag, or null. I'm okay with this approach too; I just need to try it out to see if it looks good. I might also need to test it against different compiler vendors, because I'm not sure how other compilers handle the order and repetition of macro (argument) expansion.
The next phase of commits will have to add logging information (log tags) to each OpenCV module, to see how it behaves. (In particular to see whether it achieves the desirable log filtering effect.) These attempts are experimental (i.e. not to be kept), so should I submit a separate PR? It would have to depend on the current PR. Or I could rebase and squash.
My assumption is that declaration of "tag" identifier includes implicit tag registration call - this would avoid manual tag registration calls from "users".
I believe most part of "work" should be hidden from users. There are already CV_TRACE_FUNCTION(); (or CV_INSTRUMENT_REGION()) statements across OpenCV functions, so we can bind logging tag registration into this macros.
Feel free to experiment in a single PR - rebase & squash is fine.
(timestamp 2019-03-06T04:29:40Z)
Added LogTagAuto for auto registration in ctor
This commit implements a class LogTagAuto which is derived from LogTag and which auto-registers with LogTagManager at constructor time. The intended use is to define static instances of LogTagAuto in namespace scope, and then refer to this tag either explicitly (when calling CV_LOG_WITH_TAG), or implicitly (by re-defining CV_LOGTAG_FALLBACK within a compilation unit (cpp file)).
For each compilation unit (cpp file), the changes are:
Initialize a static instance of LogTagAuto with instance name, the log tag string, the default log filtering threshold level in absence of any applicable configuration.
The re-definition of the CV_LOGTAG_FALLBACK macro, which causes all the CV_LOG_* macro invocations that specify NULL as the tag argument to automatically pick up the LogTagAuto static variable that we just defined.
The minimum number of lines of change per compilation unit is 3:
One line for LogTagAuto
Two lines for re-defining a macro (#undef and #define).
We can safely assume CV_LOGTAG_FALLBACK is always defined (as an identity function, in logger.hpp), so we don't need to check for existence.
Because this involves preprocessor directives, it is not possible to "automate" with preprocessor magic.
The use of the anonymous namespace for the LogTagAuto is optional, as it currently serves no purpose.
Anticipation of introduced difficulties with respect to ongoing merging and backporting activities between 3.4 and master branches.
The insertion of LogTagAuto declaration is straightforward and could be easily scripted. However, the nuance that require human insight and involvement is to determine the correct point of insertion: the line number on which the LogTagAuto declaration and macro redefinition shall be inserted.
It is possible to develop scripting tools that can temporarily remove and re-apply these lines of code, but a human reviewer will need to provide some hints to this tool so that those lines are always inserted at the correct place.
Is it possible to set call back from other library or application to redirect messages from cout, cerr?
It is common approach for libraries (as mentioned in #11003 (comment))
The simple callback void opencv_logger_callback(int level, const char* message) would be enough.
Reacted by Ryan Wong, Abdelaziz Mahdy and Patrik Huber
I found this thread via search engine and came here to post exactly what @sbellus posted. Currently, there is some logging in OpenCV (e.g. videoio plugin_loader), and it just goes to stdout. It can be disabled. But what would be great if there indeed was just a simple function cv::utils::logging::setLoggingCallback(...) that would allow me to forward OpenCV's log messages to my own logger. @vpisarev, @kinchungwong?
I have opened a Draft PR #27140 as a starting point for discussion. There're a number of difficulties and pending issues, which is why I haven't worked on this for the last few years. Of those the biggest issue is trying to eliminate race conditions while having good performance at the same time. Configurability and flexibility is another lacking point. I gratefully appreciate all of the suggestions and guidance, especially on implementation techniques that could be borrowed from other libraries.
When both performance and safety are considered, though, here is what I have seen (or what others have been saying):
Implementation
Speed
Safety
libc printf, where we control fmt and sizeof(buf)
fastest
safe, if care is taken in size calculations
std::string
direct operations: fastest; to_string() methods: okay, overhead from temporary objects
best (widely available; non-crashing; okay to use during startup/shutdown/multithreaded)
std::ostringstream
slow to initialize and destroy
good, except during startup/shutdown/race conditions
There are other tiny string formatting libraries that catch up with the performance of libc printf, but seldom beat it.
The use of operator<< has its linguistic charm; it simplifies library code (i.e. invariant validations) where it matters most. We'd like to be able to keep the existing pattern, but try to match the performance of printf, without compromising on safety.
Activity
kinchungwong commentedon Jan 14, 2019
I have a list of basic opinions about what logging should do: https://gist.github.com/kinchungwong/ad3b3f7eaf34411f83bf9c393a925e14
I am prototyping some ways of addressing point 2 (enable/disable based on component, module, class, or source file name) and point 3 (some thread-level awareness and locality). But before I continue, I would like to confirm several things:
kinchungwong commentedon Jan 15, 2019
Of the list of thoughts and functionalities of logging I just shared (same link as above), I would like to know how the team would like to prioritize these features.
Right now I do not know whether conflicts will exist between these features. Typically, C++ logging frameworks must strike a balance between compile-time control and run-time control. I will post more design documents and code samples when they are ready.
I would like to know what would be proper design versus over-design (over-engineering). It is quite easy to be over-engineering on logging.
alalek commentedon Jan 15, 2019
IMHO, Tracing / logging should be kept separately.
ITT is just backend for performance tracing. It can be turned off during compilation / in runtime.
The similar things (backends) should be supported for logging:
OpenCV responsibility here is still "configuration" of logging topics/categories/tags/levels and probably basic formatting.
Logging backends are sinks with own formatting and with/without own filters configuration.
For example, "Network" / out of process sink support should be supported via some logging backend.
We prefer avoid "hard" bind of OpenCV logging API to "glog" only.
But it looks like complicated / over-engineering. So lets start from something that we need to have in OpenCV.
kinchungwong commentedon Jan 15, 2019
@alalek Some sample source code, to get the discussion going: https://gist.github.com/kinchungwong/5571608831f6ddbb36addb994e1b04d1
This sample source code is just to illustrate some of the points and functionalities discussed earlier. It is also a learning experience - to know what implementation techniques are valuable, feasible, undesirable, or outright impractical.
I will summarize the lessons learned. Here's an incomplete list:
operator <<) is a nice way to get around C++ macro expansion issues when a variable number of items need to be passed.LOGGING_TEST_MACRO(3, LOG_LOC() << LOG_THIS(), "hello " << "there");Non-lessons:
alalek commentedon Jan 17, 2019
@kinchungwong Thank you for working on this!
setLogFilter,getLogFilterandLogFilterFunctionTypeapproach has some issue: filter check function impact can be significant for regular frequent calls (not matter if event logged or it is skipped), includingstrcmp()calls or regex processing.Minimal cost effective check may look like this:
What is "log_entry_scope"?
Main magic here is "scope" configuration. I believe we can re-use tree-based structure.
Example of tree levels:
LOG_...()macro: with exact file/line/function nameConfigured value is:
opencv_imgcodecs.imread = DEBUGSeparate large entity of logger is "configurator":
BTW, "tag" in current macros implementation is placeholder for metadata / "parent" log entry scope:
static LogModule log_module("imgcodecs");(declared once per module in global scope)static LogFunction log_function(l_module, "imread");l_moduleis a parent scope in configuration tree`LOG_DEBUG(log_module, "imread() called");expands to something like this:
LOG_INFO(log_function, "Open file: " << fname << "...");Class instances.
We should have non-global logging descriptors if we want to log events from different class instances separately.
Descriptors are not global "c++ static", they can be stored as class fields.
Q: Should we use other metadata for extra filtering?
Filtering by thread ID
Using TLS can slowdown checks. Can be implemented as second-level additional check.
kinchungwong commentedon Jan 18, 2019
@alalek Here is a new set of sample code to illustrate my understanding of your latest suggestion: https://gist.github.com/kinchungwong/aac811321766d7ea0782011ba72cdd71
The sample code is quite involved, but certain things can be potentially simplified. For example, there is no need for classes
ClassDynamicInfoorFunctionDynamicInfo, if the entire "dynamic information" we intend to share (to centrally manage and locally cache) is anint logLevel. We can just store and share a pointer to that integer.I have just finished writing up the code, haven't got to summarizing the design elements or learned lessons. I will update the Gist with some write-up a few days later, possibly during the weekend.
This sample code could be buggy. I haven't fully conceptualized all of the object lifetime issues. There may be dangling references to expired temporary objects.
kinchungwong commentedon Jan 19, 2019
@alalek I have updated the sample code I posted on the Gist from my last comment. Same link: https://gist.github.com/kinchungwong/aac811321766d7ea0782011ba72cdd71
I have removed
ModuleNameetc, choosing to combine the string class functionality intoModuleInfoetc.The earlier
DynamicInfoManagerhas a subtle "order of static initialization` bug. It is fixed by moving static members into a nested class, and to guarantee its initialization by making it a static local member of a function. (This is the standard practice for resolving this type of bugs.)I have added a
LogLevelManagerclass. This class is not actually needed; I added it so that I can put four related static (non-member) functions there. These functions are the entry point for getting and setting the log level of anything within the capability of this framework. The functions are:Scope is a string with one, two, or three parts:
ConfigLayer is a necessary evil to solve a well-known problematic phenomenon in software configuration - that of clobbering of configs when multiple sources of configs are applied, often applied in a wrong order that's inconsistent with their intended precedence (that a human would expect). I can explain why this design is necessary in maybe 1000 words or so. To put it simply, this is something we can't omit.
With this sample code, I have learned enough about the domain and the requirements so that I can start writing a specification. The specification should be ready by Tuesday.
I also realized that, with the specification I have in mind, this sample code isn't the most efficient implementation. There're lots of rooms for efficiency improvement.
One thing that I have validated through this sample code, is that the overhead of repeated calls to the same function (for example, calling LogLevelManager.Check() using the same FunctionInfo object that's already initialized, can be fast enough that my measured TSC count per repeated call can be as low as 8 - 15. However, the first time initialization (either first-time setting or first-time getting a particular scopes log level cutoff) is quite expensive, with measured TSC count in thousands or tens of thousands, with the current sample code.
I'll now focus on writing the specification, expected to be ready by Tuesday.
kinchungwong commentedon Jan 23, 2019
Spec
Log levels
Scope-based log filtering
Log scope
Using log scope for meanings other than module, class, and function
Configuration layers
Background: about the necessity of configuration layers
Calculation of the effective filtering threshold for a given log message
Table - the order of checking scopes and configuration layers for the effective filtering threshold
Row: config layer
alalek commentedon Jan 24, 2019
Agree!
Information may be separated into:
int logLevel(unique for each class instance)In this case, configuration manager has "pointers" on these entities:
My two last comments are related to wider "OpenCV configuration" issue (there is no such "OE" item).
Logging is a good example / starting point of capturing configuration's problems.
I believe this should be simplified.
We store one value for configuration leaf. And we check this value only.
This value is set by:
kinchungwong commentedon Jan 24, 2019
@alalek Thanks for your reviews and comments.
My latest commit https://github.com/kinchungwong/opencv/commit/2a337b4b6ca9e5166f727700847a525444420891 is based on my spec #11003 (comment) ; it hasn't incorporated your latest feedback yet.
My latest comment consist of:
(These are links to the buildbot result; links might become broken)
However, based on my experience and opinion, parts of your latest suggestions might be difficult or error-prone to implement. I'll explain below.
Regarding the general questions of "who owns what" and "who has pointers to what", my current design is prepared for the following situations:
Regarding order of initialization, in particular "when config is loaded" and "when the scope of ModuleOne.ClassA is first entered"
If config is loaded before the static members of ModuleOne.ClassA can be initialized, the LogManager has to parse the config first, but delay the propagation of the data.
Whereas, in my current PR, it does not matter whether the config change comes from initialization or first-time-of-use. It will get a pointer (reference) to the configuration record, and it can read/write directly, without asking LogManager again.
I'm also mindful of the static initialization order fiasco, and I try to consciously make sure my design is compliant, though I may sometimes make some bugs.
Regarding multithreading operations:
getLogThresholdandsetLogThreshold). This is a coarse-grained lock.std::unordered_mapis slow and requires locking for all (read and write) multi-threaded operations.Regarding performance, in particular measurement of execution and memory overheads:
I'll continue to explore the boundary of possibilities, to see if there're rooms for enhancement.
kinchungwong commentedon Jan 24, 2019
I'd like to clarify this a little bit.
In practice, it consists of a maximum of three calls to LogManager:
Calls which are not the first time are guaranteed to make zero calls to LogManager. It will go ahead and read from a LogThreshold via a pointer, which is "the configuration data record".
mshabunin commentedon Jan 25, 2019
These log scopes looks overcomplicated to me. Can we just use some sort of log tags like other libraries/frameworks?
Examples:
GStreamer
https://gstreamer.freedesktop.org/documentation/tutorials/basic/debugging-tools.html
export GST_DEBUG=5=> log level set to 5 (DEBUG) for all messagesexport GST_DEBUG=2,audiotestsrc:6=> log level set to 6 (LOG) for the audiotestsrc element, and 2 (WARNING) for all the othersexport GST_DEBUG=2,audio*:6=> log level set to 6 (LOG) for all categories starting with the word audio, and 2 (WARNING) for all othersAndroid
https://developer.android.com/studio/command-line/logcat#filteringOutput
adb logcat ActivityManager:I MyApp:D *:Swill set log level to Info for ActivityManager, Debug for MyApp and Silent for all other messages.FFmpeg
https://ffmpeg.org/doxygen/3.2/group__lavu__log.html
void av_log_set_callback (void(*callback)(void *, int, const char *, va_list))allows user to set custom callback which will handle all log messages.Qt
http://doc.qt.io/qt-5/qtglobal.html#qInstallMessageHandler
qInstallMessageHandlerallows user to set custom callback which will handle all log messageshttp://doc.qt.io/qt-5/qmessagelogcontext.html
Log context struct which contains category (log level), file (FILE), function (FUNCTION), line (LINE) and version fields.
My proposal
We can slightly tune existing logging facility to add log tags (like in GStreamer), filtering based on tags (like in GStreamer and Android), simple log context (like in Qt) and an interface to override low level logging function (like in FFmpeg and Qt).
I thinke these scopes are too complicated because there can be: namespaces, class inside a class, lambda functions. I don't see how these can be implemented in a reliable way.
kinchungwong commentedon Jan 26, 2019
@mshabunin Please review my latest proof-of-concept design: https://gist.github.com/kinchungwong/0af6b6535c35e70c3dc1f7d63a355cfc
I agree that hierarchical log scope can be over-complicated. However, let's not forget that, both wildcard matching and hierarchical log scope searching can be expensive at runtime, if done repeatedly. Any attempt to reduce the amount of work will lead to creation of classes and static objects to cache their results.
But for now, I will present a proof-of-concept design that doesn't do either. Thus, the "tag" must match exactly, as there is no hierarchical setting or wildcard matching.
Line-of-code filtering, i.e. turning on/off logging based on
__FILE__, __LINE__, __FUNCTION__is also expensive at runtime. I haven't found out a good way to make it fast. I'd like to hear suggestions from your team.I also agree that we should start with the logging macro first (see code) - to envision what the logging macro should look like.
I think we have consensus that the following information will be always captured: log level, tag, file, line, function, time, thread ID.
The "tag" is just a string. However, I think it is appropriate to apply "convention over configuration" thinking here. Why not do this:
Example:
(these lines of code can be found in my latest proof-of-concept design, same link as above.)
To make this internally-declared integer values configurable centrally, a piece of registration code is needed:
Regarding thread ID, the least-expensive thread ID that can be computed should be used. Typically, the native thread ID handle is the least-expensive (it is a read from a special location). It is also the case that the native thread ID makes the most sense to programmers.
3 remaining items
kinchungwong commentedon Feb 15, 2019
An approach that avoids the issues of MSVC DLL import/export of variables (as opposed to functions) mentioned in #13836
Throughout this document, unless otherwise specified, any identifiers that contain
the substring "TBD" (short for "to be determined") implies that the actual naming
scheme for these identifiers will be defined at a later time, and through such
future definition it can be guaranteed that accidental name collisions of
identifiers cannot happen.
Example
In the following example, some lines of code are followed by a line of comment
consisting of dots ("."), carets ("^"), and underscores ("_").
The carets indicate the tag that must match exactly in order for the
preprocessor macro expansion to work.
The underscores indicate part of the C++ identifier name of the log level variable.
Its name does not have to be the same as the tag (although it is advantageous to be so),
because it is not an input to the preprocessor macro expansion (it is the result of that expansion).
This example uses
"leaky_water_pipes"as a fictitious OpenCV module or scope name.Macro CV_TBD_LOG
prototype
CV_TBD_LOG(tag, level, v, msg_args)CV_TBD_LOG(tag, level, v, file, line, func, msg_args)arguments
tag: an unqouted string (preprocessor token), to be used in preprocessor operators such astoken pasting, stringification, etc. See Preprocessor Expansion section below.
level: a C++ expression (of enum LogLevel) that evaluates to the loglevel of the message.
v: a C++ integer expression that specifies the verbosity sub-levelfor all log messages sent at the VERBOSE level. A verbosity sub-level can be
thought of as a fine-grane subdivision of the VERBOSE level. This parameter
must be zero if the log level of the message is not VERBOSE.
msg_args: one or more arguments to the C++ stream insertion operatorthat provides input to the formatting of the log message content.
Preprocessor Expansion of the
tagargumentThe
tagargument will be expanded as follows:preprocessor macro with a prescribed prefix. Each use of logging
statement should ensure that the preprocessor macro formed formatting
this token-pasting is actually defined.
allows the log level variable to be manipulated programmatically.
The log level variable
CV_LOGLEVEL_##tag, orCONCAT(CV_LOGLEVEL_, tag)The result of this expansion shall be another preprocessor macro; this
preprocessor macro can be defined before or after the definition of
CV_TBD_LOG.Usually,
CV_TBD_LOGis defined in a header inmodules/core/include,and the
CV_LOGLEVEL_tagis defined inside each OpenCV module.This macro shall evaluate to a C++ expression that yields the log filtering
threshold applicable to that tag. In particular, it is permissible for that
expression to be:
Each of these choices bring capabilities and limitations. When implementing
logging for each module and scope, the choice should be made after careful
consideration of the specific needs within each module and scope.
Explanation
The prefix "CV_LOGLEVEL_" is pasted together with "diagonstics" to form
"CV_LOGLEVEL_diagnostics". This preprocessor macro needs to have been defined
before the logging statement.
In this example, the actual log level variable only needs to be accessible
within this module or dynamic library (
"*.DLL"or"*.so").Therefore, the variable can be declared
externin a header that isvisible within the module, and then the definition (initialization) can be
placed into one of the compilation units (in exactly one
"*.cpp"file).Allowing programmatic access to log level variable by a string key
A helper class
cv::LogLevelRegistrationis to be created. Its constructormethod should take a string and a reference (or pointer) to a mutable log level
variable. The constructor should call the
LogManagerclass for the nameand variable to be added to a lookup table (similar to
std::unordered_map).The registration can be scheduled to happen at
Deferred dynamic initialization.
However, the relative order between deferred dynamic initialization and other
code is not specified. In other words, it is possible that some code and logging
statements may have been executed while referencing uninitialized log level variables,
or that programmatic access to log level variables by string name may not find
a match because the registration code has not yet executed.
kinchungwong commentedon Feb 25, 2019
(PR #13909 replaces PR #13642 because the old PR was too different from the current design and is not salvageable.)
kinchungwong commentedon Feb 27, 2019
I'll explain why I decided not to do this:
This page (on my Gist) explains why I decided not to use the preprocessor token-pasting technique (the
##operator in preprocessor) to expand tag name into more than one C++ identifiers (tag name and log level).The basic reason is that token-pasting is incompatible with the use of C++ expressions. Let's say someone enclosed the C++ expression inside a pair of parentheses, as in
(expr), and pass it into a C++ preprocessor macro. The token pasting result is thenprefix_(expr), which is not the desired result.For token-pasting and the use of C++ expressions (when calling a C++ preprocessor macro) to co-exist, the C++ expressions need to have no symbols (brackets of any kind, period, ampersand (address-of operator), asterisk (dereference operator), etc) on the left side of the macro's input argument.
However, based on my implementation attempts, I conclude that this is too restrictive. I also concluded that the logging macro needs to be allowed to accept a C++ expression for the "tag" argument. Therefore, preprocessor token-pasting approach cannot be used on the "tag" argument.
As seen in this page (on my Gist) linked above, there are still many ways to use macro expansions that give valid expansion result. Thus, I'm not forbidding the use of all preprocessor techniques; I'm just choosing not to apply token-pasting on the "tag" argument.
alalek commentedon Feb 27, 2019
I believe we should not allow to use custom expressions here.
If someone wants some custom tag, then it should declare its "identifier" above (via additional macro). And then use this identifier - we should have such declarations for each module/file(.cpp)/function/class/method.
Additionally, tag
prefix_implements some compile-time checks to avoid typos or misusing (it is too easy, for example, with "int"-like type of result).kinchungwong commentedon Feb 28, 2019
@alalek not only
(expr), but&exprwill also give bad result. Consider this: user wants to pass in the address of something as tag, and naturally puts&in front of the actual variable.In other words, token pasting forces us to require logging users to specify the tag in exactly one way: it has to be the suffix of the name of a macro (which needs to be defined by logging user), and
CV_LOGwill automatically apply the prefixCV_LOGTAG_ ## tagto it and then expand it. The expansion result needs to be a pointer toLogTag, or null. I'm okay with this approach too; I just need to try it out to see if it looks good. I might also need to test it against different compiler vendors, because I'm not sure how other compilers handle the order and repetition of macro (argument) expansion.The next phase of commits will have to add logging information (log tags) to each OpenCV module, to see how it behaves. (In particular to see whether it achieves the desirable log filtering effect.) These attempts are experimental (i.e. not to be kept), so should I submit a separate PR? It would have to depend on the current PR. Or I could rebase and squash.
alalek commentedon Feb 28, 2019
My assumption is that declaration of "tag" identifier includes implicit tag registration call - this would avoid manual tag registration calls from "users".
I believe most part of "work" should be hidden from users. There are already
CV_TRACE_FUNCTION();(orCV_INSTRUMENT_REGION()) statements across OpenCV functions, so we can bind logging tag registration into this macros.Feel free to experiment in a single PR - rebase & squash is fine.
kinchungwong commentedon Mar 6, 2019
@alalek
About LogTag auto-registration, usage example, code impact
Commit ca9d0b1
(timestamp 2019-03-06T04:29:40Z)
Added LogTagAuto for auto registration in ctor
This commit implements a class LogTagAuto which is derived from LogTag and which auto-registers with LogTagManager at constructor time. The intended use is to define static instances of LogTagAuto in namespace scope, and then refer to this tag either explicitly (when calling CV_LOG_WITH_TAG), or implicitly (by re-defining CV_LOGTAG_FALLBACK within a compilation unit (cpp file)).
Commit 0a50c6f
(timestamp 2019-03-06T04:33:30Z)
EXCLUDE_ON_NEXT_REBASE demo logtag usage
This demo-only commit shows how LogTagAuto and CV_LOGTAG_FALLBACK are used together.
The demo change is applied to a limited number of files, in opencv_core:
For each compilation unit (cpp file), the changes are:
The minimum number of lines of change per compilation unit is 3:
#undefand#define).The use of the anonymous namespace for the LogTagAuto is optional, as it currently serves no purpose.
Anticipation of introduced difficulties with respect to ongoing merging and backporting activities between 3.4 and master branches.
The insertion of LogTagAuto declaration is straightforward and could be easily scripted. However, the nuance that require human insight and involvement is to determine the correct point of insertion: the line number on which the LogTagAuto declaration and macro redefinition shall be inserted.
It is possible to develop scripting tools that can temporarily remove and re-apply these lines of code, but a human reviewer will need to provide some hints to this tool so that those lines are always inserted at the correct place.
kinchungwong commentedon Mar 20, 2019
Latest revised spec. It is possible that this spec may survive even if my code contribution become abandoned. https://github.com/kinchungwong/opencv_OE11_logging_11003_wiki/blob/master/spec_revised_20190320.md
Merge pull request opencv#13909 from kinchungwong:logging_20190220
sbellus commentedon Jul 14, 2023
Is it possible to set call back from other library or application to redirect messages from cout, cerr?
It is common approach for libraries (as mentioned in #11003 (comment))
The simple callback
void opencv_logger_callback(int level, const char* message)would be enough.patrikhuber commentedon Mar 22, 2025
I found this thread via search engine and came here to post exactly what @sbellus posted. Currently, there is some logging in OpenCV (e.g. videoio plugin_loader), and it just goes to stdout. It can be disabled. But what would be great if there indeed was just a simple function
cv::utils::logging::setLoggingCallback(...)that would allow me to forward OpenCV's log messages to my own logger.@vpisarev, @kinchungwong?
kinchungwong commentedon Mar 24, 2025
@sbellus @patrikhuber
I have opened a Draft PR #27140 as a starting point for discussion. There're a number of difficulties and pending issues, which is why I haven't worked on this for the last few years. Of those the biggest issue is trying to eliminate race conditions while having good performance at the same time. Configurability and flexibility is another lacking point. I gratefully appreciate all of the suggestions and guidance, especially on implementation techniques that could be borrowed from other libraries.
Allow OpenCV user register for logging callback.
kinchungwong commentedon Mar 27, 2025
Concerning the use of
std::ostringstreamin logging, I have created a minimal prototype that mimics itsoperator<<()functionality.https://github.com/kinchungwong/opencv_small_string_formatter
When both performance and safety are considered, though, here is what I have seen (or what others have been saying):
fastest;
to_string() methods:
okay, overhead from temporary objects
There are other tiny string formatting libraries that catch up with the performance of libc printf, but seldom beat it.
The use of
operator<<has its linguistic charm; it simplifies library code (i.e. invariant validations) where it matters most. We'd like to be able to keep the existing pattern, but try to match the performance of printf, without compromising on safety.Merge pull request opencv#13909 from kinchungwong:logging_20190220