Flexible registrar class using standard streams in C ++

I would like to create a flexible journal class. I want it to be able to output data to a file or to standard output. In addition, I want to use streams. The class should look something like this:

class Logger
{
private:
   std::ostream m_out; // or ofstream, iostream? i don't know
public:

   void useFile( std::string fname);
   void useStdOut();

   void log( symbol_id si, int val );
   void log( symbol_id si, std::string str );
   //etc..
};

symbol_id- This listing defines formatting. What I want to achieve is to easily switch from standard output to a file and vice versa (this is the purpose of the methods use*). Preferably, just using m_outand just writing m_out << "something";without any checks, do I want to write to a file or standard output.

, ( if's, , stdout, "C way" ( FILE* fprintf)) .., , , ++ . , . - ?

+5
4

, , , Logger FileLogger OutStreamLogger. CompositeLogger, Logger, :

CompositeLogger compLogger;
compLogger.Add(new FileLogger("output.txt"));
compLogger.Add(new StreamLogger(std::cout));
...
compLogger.log(...);

, m_Out std::ostream , , :

private:
  std::ostream*   m_out;
  bool            m_OwnsStream;

Logger() {
   m_Out=&std::cout; // defaults to stdout
   m_OwnsStream=false;
}
void useFile(std::string filename) {
  m_Out=new std::ofstream(filename);
  m_OwnsStream=true;
}
~Logger() {
  if (m_OwnStream) 
    delete m_Out; 
}

, useFile useStdOut, .

+8

std::o*stream ++ std:: ostream. , std:: ofstream :

class Logger
{
    std::ostream *m_out; // use pointer so you can change it at any point
    bool          m_owner;
public:
    // constructor is trivial (and ommited)
    virtual ~Logger()
    {
        setStream(0, false);
    }
    void setStream( std::ostream* stream, bool owner )
    {
        if(m_owner)
            delete m_out;
        m_out = stream;
        m_owner = owner;
    }
    template<typename T>
    Logger& operator << (const T& object)
    {
        if(!m_out)
            throw std::runtime_error("No stream set for Logger class");
        (*m_out) << object;
        return *this;
    }
};

// usage:
Logger logger;
logger.setStream( &std::cout, false ); // do not delete std::cout when finished
logger << "This will be logged to std::cout" << std::endl;
// ...
logger.setStream( 
    new std::ofstream("myfile.log", std::ios_base::ate|std::ios_base::app), 
    true ); // delete the file stream when Logger goes out of scope
logger << "This will be appended to myfile.log" << std::endl;
+9

The_mandrill solution, for this I thought that the strategy template would better fit this problem, conceptually. We can change the logging strategy at any time simply by calling context-> SetLogger.
We can also use different files for the file recorder.

class Logger
{
protected:
    ostream* m_os;
public:
    void Log(const string& _s)
    {
        (*m_os) << _s;
        m_os->flush();
    }
};

class FileLogger : public Logger
{
    string m_filename;
public:
    explicit FileLogger(const string& _s)
    : m_filename(_s)
    {
        m_os = new ofstream(m_filename.c_str());
    }
    ~FileLogger()
    {
        if (m_os)
        {
            ofstream* of = static_cast<ofstream*>(m_os);
            of->close();
            delete m_os;
        }
    }
};

class StdOutLogger : public Logger
{
public:
    StdOutLogger()
    {
        m_os = &std::cout;    
    }
};

class Context
{
    Logger* m_logger;
public:
    explicit Context(Logger* _l)  {m_logger = _l;}
    void SetLogger(Logger* _l)    {m_logger = _l;}
    void Log(const string& _s)
    {
        if (m_logger)
        {
            m_logger->Log(_s);
        }
    }
};

int main()
{
    string filename("log.txt");

    Logger*  fileLogger   = new FileLogger(filename);
    Logger*  stdOutLogger = new StdOutLogger();
    Context* context      = new Context(fileLogger);

    context->Log("this log out to file\n");
    context->SetLogger(stdOutLogger);
    context->Log("this log out to standard output\n");
}
+2
source

All Articles