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

View file

@ -1,6 +1,7 @@
#pragma once
#include <string>
#include <fstream>
class Log
{
@ -23,7 +24,9 @@ class Log
static Log* instance();
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)