cpp-common/bt2c: optionally log and append errors in `dataFromFile()`
authorSimon Marchi <simon.marchi@efficios.com>
Thu, 25 Apr 2024 14:57:24 +0000 (14:57 +0000)
committerSimon Marchi <simon.marchi@efficios.com>
Wed, 4 Sep 2024 19:05:14 +0000 (15:05 -0400)
For some callers, a `dataFromFile()` error (`NoSuchFileOrDirectoryError`
typically) may be fatal, in which case it would be appropriate to log an
error and append an error cause.  For others callers, it might not be
fatal, they just want to catch the exception and carry on.

To accomodate this, pass a logger to `dataFromFile()` and add a
`fatalError` boolean parameter.  Log an error and append an error cause
on error if `fatalError` is true.  Otherwise, log at the debug level.

Change-Id: Id32639b16a928195bc430c1a2ce7671ced2ad43b
Signed-off-by: Simon Marchi <simon.marchi@efficios.com>
Reviewed-on: https://review.lttng.org/c/babeltrace/+/12738
Reviewed-by: Philippe Proulx <eeppeliteloop@gmail.com>
Tested-by: jenkins <jenkins@lttng.org>
src/cpp-common/bt2c/file-utils.cpp
src/cpp-common/bt2c/file-utils.hpp

index 9352018229541643dfef561efe49c4bb74e67f7a..de5e3e194e499876cf4b4ebc447d9c0fdf75b2ac 100644 (file)
@@ -6,12 +6,15 @@
  */
 #include <fstream>
 
+#include "logging.hpp"
+
 #include "exc.hpp"
 #include "file-utils.hpp"
 
 namespace bt2c {
 
-std::vector<std::uint8_t> dataFromFile(const char * const filePath)
+std::vector<std::uint8_t> dataFromFile(const char * const filePath, const Logger& logger,
+                                       const bool fatalError)
 {
     /*
      * Open a file stream and seek to the end of the stream to compute the size
@@ -20,6 +23,14 @@ std::vector<std::uint8_t> dataFromFile(const char * const filePath)
     std::ifstream file {filePath, std::ios::binary | std::ios::ate};
 
     if (!file) {
+        constexpr const char *msg = "No such file or directory: path=\"{}\"";
+
+        if (fatalError) {
+            BT_CPPLOGE_APPEND_CAUSE_SPEC(logger, msg, filePath);
+        } else {
+            BT_CPPLOGD_SPEC(logger, msg, filePath);
+        }
+
         throw NoSuchFileOrDirectoryError {};
     }
 
index 17bbe8c3e6b430bf59a7e91f2909d67093b19caa..9193d12e68e83053a4ecb168453d37dbe1210230 100644 (file)
 
 namespace bt2c {
 
+class Logger;
+
 /*
  * Returns a vector of all the bytes contained in `path`.
+ *
+ * Throws `NoSuchFileOrDirectoryError` if the file does not exist.
+ *
+ * If `fatalError` is true, log an error and appends an error
+ * cause prior to throwing.  Otherwise, log at the debug level.
  */
-std::vector<std::uint8_t> dataFromFile(const char *path);
+std::vector<std::uint8_t> dataFromFile(const char *path, const Logger& logger, bool fatalError);
 
 } /* namespace bt2c */
 
This page took 0.025982 seconds and 4 git commands to generate.