Use fstream to open and write to log file and include process ID in log entries.

This commit is contained in:
Robert Knight 2011-08-21 22:56:33 +01:00
parent e4a427b9e2
commit 93274ed348
2 changed files with 36 additions and 14 deletions

View file

@ -1,53 +1,72 @@
#include "Log.h" #include "Log.h"
#include <sys/types.h> #include "Platform.h"
#include <sys/stat.h> #include "StringUtils.h"
#include <fcntl.h>
#include <string.h> #include <string.h>
#include <iostream> #include <iostream>
#ifdef PLATFORM_UNIX
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif
Log m_globalLog; Log m_globalLog;
#ifdef PLATFORM_UNIX
pid_t currentProcessId = 0;
pid_t processId()
{
if (currentProcessId == 0)
{
currentProcessId = getpid();
}
return currentProcessId;
}
#endif
Log* Log::instance() Log* Log::instance()
{ {
return &m_globalLog; return &m_globalLog;
} }
Log::Log() Log::Log()
: m_fd(-1)
{ {
} }
Log::~Log() Log::~Log()
{ {
close(m_fd);
} }
void Log::open(const std::string& path) void Log::open(const std::string& path)
{ {
m_fd = ::open(path.c_str(),S_IRUSR); m_output.open(path.c_str());
} }
void Log::write(Type type, const char* text) void Log::writeToStream(std::ostream& stream, Type type, const char* text)
{ {
switch (type) switch (type)
{ {
case Info: case Info:
std::cerr << "INFO "; stream << "INFO ";
break; break;
case Warn: case Warn:
std::cerr << "WARN "; stream << "WARN ";
break; break;
case Error: case Error:
std::cerr << "ERROR "; stream << "ERROR ";
break; break;
} }
std::cerr << text << std::endl; stream << '(' << intToStr(processId()) << ") " << text << std::endl;
}
if (m_fd >= 0) void Log::write(Type type, const char* text)
{ {
::write(m_fd,text,strlen(text)); writeToStream(std::cerr,type,text);
if (m_output.is_open())
{
writeToStream(m_output,type,text);
} }
} }

View file

@ -1,6 +1,7 @@
#pragma once #pragma once
#include <string> #include <string>
#include <fstream>
class Log class Log
{ {
@ -23,7 +24,9 @@ class Log
static Log* instance(); static Log* instance();
private: private:
int m_fd; static void writeToStream(std::ostream& stream, Type type, const char* text);
std::fstream m_output;
}; };
inline void Log::write(Type type, const std::string& text) inline void Log::write(Type type, const std::string& text)