Allow to display time in perf debug output via new
debug_set_display_time function.

It will be used in perf daemon command to get verbose
output into log file.

The debug time format is:

  [2020-12-03 18:25:31.822152] affinity: SYS
  [2020-12-03 18:25:31.822164] mmap flush: 1
  [2020-12-03 18:25:31.822175] comp level: 0
  [2020-12-03 18:25:32.002047] mmap size 528384B

Signed-off-by: Jiri Olsa <jo...@kernel.org>
---
 tools/perf/util/debug.c | 34 +++++++++++++++++++++++++++++++---
 tools/perf/util/debug.h |  1 +
 2 files changed, 32 insertions(+), 3 deletions(-)

diff --git a/tools/perf/util/debug.c b/tools/perf/util/debug.c
index 50fd6a4be4e0..dc148b08814b 100644
--- a/tools/perf/util/debug.c
+++ b/tools/perf/util/debug.c
@@ -10,6 +10,7 @@
 #include <api/debug.h>
 #include <linux/kernel.h>
 #include <linux/time64.h>
+#include <sys/time.h>
 #ifdef HAVE_BACKTRACE_SUPPORT
 #include <execinfo.h>
 #endif
@@ -31,21 +32,48 @@ int debug_ordered_events;
 static int redirect_to_stderr;
 int debug_data_convert;
 static FILE *debug_file;
+bool debug_display_time;
 
 void debug_set_file(FILE *file)
 {
        debug_file = file;
 }
 
+void debug_set_display_time(bool set)
+{
+       debug_display_time = set;
+}
+
+static int fprintf_time(FILE *file)
+{
+       struct timeval tod;
+       struct tm ltime;
+       char date[64];
+
+       if (!debug_display_time)
+               return 0;
+
+       if (gettimeofday(&tod, NULL) != 0)
+               return 0;
+
+       if (localtime_r(&tod.tv_sec, &ltime) == NULL)
+               return 0;
+
+       strftime(date, sizeof(date),  "%F %H:%M:%S", &ltime);
+       return fprintf(file, "[%s.%06lu] ", date, tod.tv_usec);
+}
+
 int veprintf(int level, int var, const char *fmt, va_list args)
 {
        int ret = 0;
 
        if (var >= level) {
-               if (use_browser >= 1 && !redirect_to_stderr)
+               if (use_browser >= 1 && !redirect_to_stderr) {
                        ui_helpline__vshow(fmt, args);
-               else
-                       ret = vfprintf(debug_file, fmt, args);
+               } else {
+                       ret = fprintf_time(debug_file);
+                       ret += vfprintf(debug_file, fmt, args);
+               }
        }
 
        return ret;
diff --git a/tools/perf/util/debug.h b/tools/perf/util/debug.h
index 43f712295645..48f631966067 100644
--- a/tools/perf/util/debug.h
+++ b/tools/perf/util/debug.h
@@ -64,6 +64,7 @@ int veprintf(int level, int var, const char *fmt, va_list 
args);
 
 int perf_debug_option(const char *str);
 void debug_set_file(FILE *file);
+void debug_set_display_time(bool set);
 void perf_debug_setup(void);
 int perf_quiet_option(void);
 
-- 
2.26.2

Reply via email to