Skip to content

Commit e46e0ea

Browse files
committed
added custom log callback
1 parent 553f097 commit e46e0ea

File tree

2 files changed

+23
-8
lines changed

2 files changed

+23
-8
lines changed

src/ReadoutDatabase.cxx

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313
typedef bool my_bool;
1414
#endif
1515

16-
ReadoutDatabase::ReadoutDatabase(const char* cx) {
16+
ReadoutDatabase::ReadoutDatabase(const char* cx, int v, const LogCallback& cb) {
17+
verbose = v;
18+
theLogCallback = cb;
1719

1820
char *db_db=nullptr, *db_user=nullptr, *db_pwd=nullptr, *db_host=nullptr;
1921
char *p=nullptr,*ptr,*lptr;
@@ -77,9 +79,7 @@ ReadoutDatabase::ReadoutDatabase(const char* cx) {
7779
goto open_failed;
7880
}
7981

80-
if (verbose) {
81-
printf("Using DB %s @ %s\n", db_db, db_host);
82-
}
82+
log("Using database " + std::string(db_db) + "@" + std::string(db_host));
8383

8484
// try to connect
8585
if (mysql_real_connect(db,db_host,db_user,db_pwd,db_db,0,nullptr,0)==nullptr) {
@@ -158,9 +158,7 @@ int ReadoutDatabase::query(int maxRetry, const char *inQuery,...) {
158158
return -1;
159159
}
160160

161-
if (verbose) {
162-
printf("Executing query: %s\n", query);
163-
}
161+
log("Executing query: " + std::string(query));
164162

165163
if (maxRetry <= 0) {
166164
maxRetry = 1;
@@ -298,3 +296,13 @@ const char* ReadoutDatabase::getError() {
298296
const char* ReadoutDatabase::getQuery() {
299297
return lastQuery.c_str();
300298
}
299+
300+
void ReadoutDatabase::log(const std::string &msg) {
301+
if (verbose) {
302+
if (theLogCallback!=nullptr) {
303+
theLogCallback(msg);
304+
} else {
305+
printf("%s\n", msg.c_str());
306+
}
307+
}
308+
}

src/ReadoutDatabase.h

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,14 @@
33
#include <stdint.h>
44
#include <vector>
55
#include <string>
6+
#include <functional>
67

78
class ReadoutDatabase {
89
public:
9-
ReadoutDatabase(const char* cx); // create a handle to DB. Connection string in the form user:pwd@host/dbname
10+
// an optional user-provided logging function for all DB-related ops
11+
typedef std::function<void(const std::string &)> LogCallback;
12+
13+
ReadoutDatabase(const char* cx, int verbose = 0, const LogCallback& cb = nullptr); // create a handle to DB. Connection string in the form user:pwd@host/dbname
1014
~ReadoutDatabase();
1115

1216
// admin database structure
@@ -42,6 +46,9 @@ class ReadoutDatabase {
4246
int maxRetry = 20; // number of query retries
4347
int retryTimeout = 50; // retry interval (milliseconds)
4448

49+
LogCallback theLogCallback;
50+
void log(const std::string &log);
51+
4552
std::string lastError = ""; // error string of last query, if any
4653
std::string lastQuery = ""; // last query executed
4754
};

0 commit comments

Comments
 (0)