Page 1 of 1

Logging to another Console window

Posted: 18 Apr 2009, 20:45
by Thund
Hi! Sorry about my poor English, I'll try my best.

First of all, I must say that I'm a POCO Libraries lover, I've been using it for logging, multithreading and and XML parsing... but now I need go a little forward... That's the point, I want run a tipical Win32 application (in native C++ and withot MFC) that has appended another window (a console window), and I want log messages to the secondary console window. I create a Logger object and a ConsoleChannel, but I don't have any idea of how to stablish a connection between console window and the ConsoleChannel (and nothing is written on that window).




Thanks :)

Re: Logging to another Console window

Posted: 18 Apr 2009, 22:53
by Thund
I have found a possible solution. It only works for Windows, and requires the creation of a new derived class. This is my code:


Code: Select all

#ifdef WIN32 // Only works for Windows SO


#include <string>

#include "Poco/Channel.h"
#include "Poco/Mutex.h"
#include "Poco/Message.h"

using Poco::Channel;
using Poco::FastMutex;
using Poco::Message;

class ConsolaWindows: public Channel

   ConsolaWindows(const ConsolaWindows&consolaWindows);

   virtual ~ConsolaWindows();

   ConsolaWindows& operator=(const ConsolaWindows&consolaWindows);

   void log(const Message& msg);


   HANDLE m_hVentana;
   static Poco::FastMutex _mutex;

#endif // WIN32


Code: Select all

#include "StdAfx.h"
#include "ConsolaWindows.h"

FastMutex ConsolaWindows::_mutex;

   SetConsoleTitleA(LPCSTR("Consola Lince3D"));
   m_hVentana = GetStdHandle(STD_OUTPUT_HANDLE);

   COORD tamBuffer = {200,200};
   SetConsoleScreenBufferSize(m_hVentana, tamBuffer);


void ConsolaWindows::log(const Message& msg)
   FastMutex::ScopedLock lock(_mutex);

   std::string strMensajeNL = msg.getText() + "\n";

   char* cMensaje = new char[strMensajeNL.size()];
   char* buffer = new char[strMensajeNL.size()];

   strcpy(cMensaje, strMensajeNL.c_str());

   va_list argptr;

   va_start(argptr, cMensaje);
   vsprintf(buffer, cMensaje, argptr);

   DWORD cCharsWritten;

      WriteConsoleA(m_hVentana, buffer, strlen(buffer), &cCharsWritten, pNULO);


If your compiler uses unicode charset, you may use unicode versions for windows API functions (WriteConsoleW and SetConsoleTitleW).