0

I want to create log over a loop. Here is a simple exampe:

#include <iostream>
#include "logging.hpp"

int main(int argc,char* argv[]){

        for(int i=1; i<argc; i++)
                Logger l(argv[i]);
        return 0;
}

And this is logging.hpp file content :

#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include <iostream>

class Logger{
        public:
                Logger(std::string msg){
                        auto console = spdlog::stdout_color_mt("console");
                        console->info(msg);
                }
};

it compiles with no problem but when I run program with more than one arguments it occurs error:

[2020-10-14 20:12:30.067] [console] [info] .<first-argument>
terminate called after throwing an instance of 'spdlog::spdlog_ex'
  what():  logger with name 'console' already exists
Aborted (core dumped)

Amir reza Riahi
  • 1,540
  • 2
  • 8
  • 34
  • I think the error message is clear : you're only allowed to create one instance. You could make the `console` logger `static`, for example. That will ensure there's only one instance in the entire program named "console" – Botje Oct 14 '20 at 16:47
  • @Botje so do you know what's the solution? – Amir reza Riahi Oct 14 '20 at 16:54
  • 1
    Are you trying to log multiple messages to `ONE` log, or to create multiple logs and write one message to each (as you do now)? – Vlad Feinstein Oct 14 '20 at 17:04

1 Answers1

2

The very quick and dirty fix is to do:

static auto console = spdlog::stdout_color_mt("console");

This will ensure there is only ever one instance, as the initializer is executed exactly once.

Botje
  • 26,269
  • 3
  • 31
  • 41