Skip to content

Commit

Permalink
changing logger to spdlog
Browse files Browse the repository at this point in the history
  • Loading branch information
martinunland committed Jan 10, 2024
1 parent e86128b commit 999c017
Show file tree
Hide file tree
Showing 18 changed files with 203 additions and 223 deletions.
5 changes: 5 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ set(OPENSSL_ROOT_DIR /usr/lib/x86_64-linux-gnu)
set(OPENSSL_LIBRARIES /usr/lib/x86_64-linux-gnu)
find_package(OpenSSL REQUIRED)

# For logging with spdlog
find_package(spdlog REQUIRED)
find_package(fmt REQUIRED) # Find fmt library


# Include OpenSSL's headers in the project
include_directories(${OPENSSL_INCLUDE_DIR})

Expand Down
10 changes: 10 additions & 0 deletions common/data/scintillation/Custom_Vitrovex_radioactivity.dat
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@
"jValue": 1.28,
"jUnit": "kg",
"jInvertUnit" : ""
},
"Ra226_ACTIVITY": {
"jValue": 4.61,
"jUnit": "kg",
"jInvertUnit" : ""
},
"Ra224_ACTIVITY": {
"jValue": 1.28,
"jUnit": "kg",
"jInvertUnit" : ""
}
}
}
Expand Down
1 change: 1 addition & 0 deletions common/framework/include/OMSim.hh
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public:
void ensureOutputDirectoryExists(const std::string &filepath);
void initialiseSimulation(OMSimDetectorConstruction* pDetectorConstruction);
void startVisualisation();
void configureLogger();
//OMSimDetectorConstruction* getDetectorConstruction();
po::options_description mGeneralArgs;

Expand Down
66 changes: 38 additions & 28 deletions common/framework/include/OMSimInputData.hh
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
/** @file
/** @file
* @brief Definition of ParameterTable and InputDataManager.
* @ingroup common
*/

#ifndef OMSimInputData_h
#define OMSimInputData_h 1

#include "OMSimLogger.hh"
#include <G4OpBoundaryProcess.hh>
#include <G4SystemOfUnits.hh>
#include <boost/property_tree/json_parser.hpp>
Expand All @@ -15,39 +16,39 @@ namespace pt = boost::property_tree;
/**
* @class ParameterTable
* @brief A utility class for managing JSON-based data tables.
*
*
* The ParameterTable class provides an interface for handling and querying JSON data
* represented in the form of a property tree of the boost library. It facilitates the extraction of specific
* parameters from loaded JSON files while also supporting units and scales. The class is
* capable of loading multiple JSON datasets, each uniquely identified by a key,
* and can perform actions such as fetching a value, checking the presence of a key,
* parameters from loaded JSON files while also supporting units and scales. The class is
* capable of loading multiple JSON datasets, each uniquely identified by a key,
* and can perform actions such as fetching a value, checking the presence of a key,
* and more.
*
* Internally, this class leverages the `boost::property_tree::ptree` to represent and
* manage the JSON data structure, which makes it easy to traverse and fetch desired
* Internally, this class leverages the `boost::property_tree::ptree` to represent and
* manage the JSON data structure, which makes it easy to traverse and fetch desired
* parameters.
*
*
* Its main use is as base class of InputDataManager, but you may use it as needed (see @ref ExampleUsageParameterTable).
*
*
* @ingroup common
*
*
* @subsection ExampleUsageParameterTable Minimal example
* @code
* ParameterTable lTable; // Create an instance of the table
* lTable.appendAndReturnTree("path/to/file.json"); // Load a JSON file into the table. The key of this file (in the following "SomeKey") is contained within the file under the variable "jName"
* G4double lValue = lTable.getValue<G4double>("SomeKey", "SomeParameter"); // Fetch a specific value using its key and parameter name
*
*
* // Parsing array content from a JSON subtree into a vector using parseKeyContentToVector
* std::vector<G4double> lVector;
* pt::ptree lSubtree = lTable.getJSONTree("SomeKey"); // Retrieving the subtree of the file
* lTable.parseKeyContentToVector(lVector, lSubtree, "keyOfArray", 1.0, false); // parsing array into vector
* @endcode
*
* @warning It's essential to ensure that the provided JSON files are formatted correctly
* and that the keys and parameters being queried exist within the loaded datasets
*
* @warning It's essential to ensure that the provided JSON files are formatted correctly
* and that the keys and parameters being queried exist within the loaded datasets
* to avoid runtime errors or unexpected behavior.
*
* @note While the class provides type templating for fetching values, care must be taken
*
* @note While the class provides type templating for fetching values, care must be taken
* to ensure the correctness of the types.
*/
class ParameterTable
Expand All @@ -65,9 +66,17 @@ public:
*/
template <typename T>
T getValue(G4String pKey, G4String pParameter)
{
const T lValue = mTable.at(pKey).get<T>(pParameter);
return lValue;
{ log_trace("Fetching parameter {} in key {}", pParameter, pKey);
try
{
const T lValue = mTable.at(pKey).get<T>(pParameter);
return lValue;
}

catch (const std::exception &e)
{
log_error("Fetching parameter {} in key {} from table failed!", pParameter, pKey);
}
}

G4bool checkIfKeyInTable(G4String pKey);
Expand All @@ -90,7 +99,7 @@ public:
void parseKeyContentToVector(std::vector<T> &pVector, pt::ptree pTree,
std::basic_string<char> pKey, G4double pScaling,
bool pInverse)
{
{ log_trace("Parsing content in key {} to a vector", pKey);
for (pt::ptree::value_type &ridx : pTree.get_child(
pKey))
{ // get array from element with key "pKey" of the json
Expand Down Expand Up @@ -124,6 +133,7 @@ public:
std::basic_string<char> pKey, G4double pScaling,
bool pInverse)
{
log_trace("Parsing content in key {} to a vector", pKey);
for (pt::ptree::value_type &ridx : getJSONTree(pMapKey).get_child(
pKey))
{ // get array from element with key "pKey" of the json
Expand All @@ -145,29 +155,29 @@ private:
/**
* @class InputDataManager
* @brief Manages the input data, including parsing and storing material properties.
*
*
* @details
* The `InputDataManager` class extends the functionalities provided by the `ParameterTable` class.
* It's dedicated to the specific needs of managing input data related to materials and optical properties
* for the Geant4-based simulation.
*
*
* You probably should have a single instance of this class (no need of loading everything twice...probably it also would break things...).
* Normally it is loaded in the main DetectorConstruction and passed to the other construction classes.
*
*
*
*
* Example usage (see also @ref ExampleUsageParameterTable):
*
*
* @code
* InputDataManager lManager;
* lManager.searchFolders(); // Search for all recognized data files in the predefined directories
* G4Material* lWater = manager.getMaterial("CustomWater"); // Retrieve a Geant4 material by name
* G4OpticalSurface* lSurface = manager.getOpticalSurface("SomeSurfaceName"); // Retrieve an optical surface by name
*
*
* auto lData = manager.loadtxt("path/to/data.txt"); // Load data from a text file into a 2D vector
* @endcode
*
*
* This class assumes certain conventions in naming and structuring the input files, which aids in automatically identifying and processing them. For example, files with names starting with "RiAbs" are treated as describing refractive and absorption properties.
*
*
* @ingroup common
*/
class InputDataManager : public ParameterTable
Expand Down
164 changes: 17 additions & 147 deletions common/framework/include/OMSimLogger.hh
Original file line number Diff line number Diff line change
@@ -1,154 +1,24 @@
/*
I Took this from a github... but I can't find it right now for giving the credits :(
*/
#define LOG_LEVEL INFO

#ifndef OMSimLogger_h
#define OMSimLogger_h 1

#include <stdio.h>
#include <time.h>

/* Default level */
#ifndef LOG_LEVEL
#define LOG_LEVEL WARNING
#endif

/* Colour customization */
#define DEBUG_COLOUR ""
#define INFO_COLOUR "\x1B[36m"
#define NOTICE_COLOUR "\x1B[32;1m"
#define WARNING_COLOUR "\x1B[33m"
#define ERROR_COLOUR "\x1B[31m"
#define CRITICAL_COLOUR "\x1B[41;1m"

/* Do not change this. */
#define RESET_COLOUR "\x1B[0m"

/* Formatting prefs. */
#define MSG_ENDING "\n"
#define TIME_FORMAT "%T"
#define BORDER "-"

/* Enabler flags */
#define DISPLAY_COLOUR 1
#define DISPLAY_TIME 1
#define DISPLAY_LEVEL 1
#define DISPLAY_FUNC 1
#define DISPLAY_FILE 1
#define DISPLAY_LINE 1
#define DISPLAY_BORDER 1
#define DISPLAY_MESSAGE 1
#define DISPLAY_ENDING 1
#define DISPLAY_RESET 1
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <memory>
#include "spdlog/fmt/fmt.h"

/* Log to screen */
#define emit_log(colour, level, file, func, line, ...) do { \
\
/* notate the time */ \
time_t raw_time = time(NULL); \
char time_buffer[80]; \
strftime(time_buffer, 80, TIME_FORMAT, localtime(&raw_time)); \
\
/* enable colour */ \
printf("%s", DISPLAY_COLOUR ? colour : ""); \
\
/* display the time */ \
printf("%s%s", DISPLAY_TIME ? time_buffer : "", DISPLAY_TIME ? " " : ""); \
\
/* display the level */ \
printf("%10s%s", DISPLAY_LEVEL ? level : "", DISPLAY_LEVEL ? " " : ""); \
\
/* display the function doing the logging */ \
printf("%s%s", DISPLAY_FUNC ? func : "", DISPLAY_FUNC ? " " : ""); \
\
/* display the file and/or the line number */ \
printf( \
"%s%s%s%.d%s%s", \
DISPLAY_FUNC && (DISPLAY_FILE || DISPLAY_LINE) ? "(" : "", \
DISPLAY_FILE ? file : "", \
DISPLAY_FILE && DISPLAY_LINE ? ":" : "", \
DISPLAY_LINE ? line : 0, \
DISPLAY_FUNC && (DISPLAY_FILE || DISPLAY_LINE) ? ") " : "", \
!DISPLAY_FUNC && (DISPLAY_FILE || DISPLAY_LINE) ? " " : "" \
); \
\
/* display message border */ \
printf("%s%s", DISPLAY_BORDER ? BORDER : "", DISPLAY_BORDER ? " " : ""); \
\
/* display the callee's message */ \
if (DISPLAY_MESSAGE) printf(__VA_ARGS__); \
\
/* add the message ending (usually '\n') */ \
printf("%s", DISPLAY_ENDING ? MSG_ENDING : ""); \
\
/* reset the colour */ \
printf("%s", DISPLAY_RESET ? RESET_COLOUR : ""); \
\
} while (0)
// Global logger instance
extern std::shared_ptr<spdlog::logger> global_logger;

/* Level enum */
#define DEBUG 0
#define INFO 1
#define NOTICE 2
#define WARNING 3
#define ERROR 4
#define CRITICAL 5
#define SILENT 6
// Custom logging function
void customLog(spdlog::level::level_enum log_level, const char* file, int line, const char* func, const std::string& message);

/* DEBUG LOG */
#define log_debug(...) do { \
if (LOG_LEVEL == DEBUG) { \
emit_log( \
DEBUG_COLOUR, "[DEBUG]", __FILE__, __func__, __LINE__, __VA_ARGS__ \
); \
} \
} while (0)
#define log_trace(...) customLog(spdlog::level::trace, __FILE__, __LINE__, __func__, fmt::format(__VA_ARGS__))
#define log_debug(...) customLog(spdlog::level::debug, __FILE__, __LINE__, __func__, fmt::format(__VA_ARGS__))
#define log_info(...) customLog(spdlog::level::info, __FILE__, __LINE__, __func__, fmt::format(__VA_ARGS__))
#define log_notice(...) customLog(spdlog::level::info, __FILE__, __LINE__, __func__, fmt::format(__VA_ARGS__))
#define log_warning(...) customLog(spdlog::level::warn, __FILE__, __LINE__, __func__, fmt::format(__VA_ARGS__))
#define log_error(...) customLog(spdlog::level::err, __FILE__, __LINE__, __func__, fmt::format(__VA_ARGS__))
#define log_critical(...) customLog(spdlog::level::critical, __FILE__, __LINE__, __func__, fmt::format(__VA_ARGS__))

/* INFO LOG */
#define log_info(...) do { \
if (LOG_LEVEL <= INFO) { \
emit_log( \
INFO_COLOUR, "[INFO]", __FILE__, __func__, __LINE__, __VA_ARGS__ \
); \
} \
} while (0)

/* NOTICE LOG */
#define log_notice(...) do { \
if (LOG_LEVEL <= NOTICE) { \
emit_log( \
NOTICE_COLOUR, "[NOTICE]", __FILE__, __func__, __LINE__, __VA_ARGS__ \
); \
} \
} while (0)

/* WARNING LOG */
#define log_warning(...) do { \
if (LOG_LEVEL <= WARNING) { \
emit_log( \
WARNING_COLOUR, "[WARNING]", __FILE__, __func__, __LINE__, __VA_ARGS__ \
); \
} \
} while (0)

/* ERROR LOG */
#define log_error(...) do { \
if (LOG_LEVEL <= ERROR) { \
emit_log( \
ERROR_COLOUR, "[ERROR]", __FILE__, __func__, __LINE__, __VA_ARGS__ \
); \
} \
} while (0)

/* CRITICAL LOG */
#define log_critical(...) do { \
if (LOG_LEVEL <= CRITICAL) { \
emit_log( \
CRITICAL_COLOUR, "[CRITICAL]", __FILE__, __func__, __LINE__, __VA_ARGS__\
); \
} \
} while (0)

#endif
//
#endif
//
2 changes: 1 addition & 1 deletion common/framework/include/OMSimUIinterface.hh
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public:
std::stringstream stream;
stream << command;
appendToStream(stream, args...);
log_debug(stream.str().c_str());
log_trace(stream.str().c_str());
UI->ApplyCommand(stream.str());
}

Expand Down
Loading

0 comments on commit 999c017

Please sign in to comment.