Commit a3b6f923617520f04e7384fc7b042094416be8c7

Authored by Eric Menezes Noronha
2 parents a943aec0 1d0c0bfe
Exists in master

Merge branch 'master' of https://github.com/lightbase/cacic-agente

Conflicts:
	cacic-teste/testcacic.cpp
	install-cacic/installcacic.cpp
cacic-daemon/cacicD/cacicD.pro
@@ -19,7 +19,7 @@ win32 { @@ -19,7 +19,7 @@ win32 {
19 LIBS += -L/usr/lib -lcryptopp 19 LIBS += -L/usr/lib -lcryptopp
20 } 20 }
21 TEMPLATE = app 21 TEMPLATE = app
22 -TEMPLATE = lib 22 +#TEMPLATE = lib
23 23
24 SOURCES += main.cpp \ 24 SOURCES += main.cpp \
25 cacicd.cpp \ 25 cacicd.cpp \
cacic-daemon/cacicD/cacicd.cpp
1 #include "cacicd.h" 1 #include "cacicd.h"
2 2
3 -cacicD::cacicD(int argc, char **argv) : QtService<QCoreApplication>(argc, argv, "CacicD") 3 +cacicD::cacicD(int argc, char **argv) : QtService<QCoreApplication>(argc, argv, "CacicDaemon")
4 { 4 {
5 try{ 5 try{
  6 + this->createApplication(argc, argv);
  7 +
6 Ocacictimer = new CacicTimer(); 8 Ocacictimer = new CacicTimer();
7 ccacic = new CCacic; 9 ccacic = new CCacic;
8 setServiceDescription("Cacic Daemon"); 10 setServiceDescription("Cacic Daemon");
9 setServiceFlags(QtService::Default); 11 setServiceFlags(QtService::Default);
  12 +
  13 + logManager = QLogger::QLoggerManager::getInstance();
  14 + logManager->addDestination(application()->applicationDirPath().append("/log.txt"),"Cacic Daemon",QLogger::InfoLevel);
  15 + logManager->addDestination(application()->applicationDirPath().append("/log.txt"),"Cacic Daemon",QLogger::ErrorLevel);
10 } catch (...){ 16 } catch (...){
11 qCritical() << "Error desconhecido no construtor."; 17 qCritical() << "Error desconhecido no construtor.";
12 } 18 }
@@ -15,7 +21,8 @@ cacicD::cacicD(int argc, char **argv) : QtService&lt;QCoreApplication&gt;(argc, argv, @@ -15,7 +21,8 @@ cacicD::cacicD(int argc, char **argv) : QtService&lt;QCoreApplication&gt;(argc, argv,
15 cacicD::~cacicD() 21 cacicD::~cacicD()
16 { 22 {
17 try{ 23 try{
18 - 24 + logManager->closeLogger();
  25 + application()->exit();
19 } catch (...){ 26 } catch (...){
20 qCritical() << "Error desconhecido no desconstrutor."; 27 qCritical() << "Error desconhecido no desconstrutor.";
21 } 28 }
@@ -23,15 +30,20 @@ cacicD::~cacicD() @@ -23,15 +30,20 @@ cacicD::~cacicD()
23 30
24 void cacicD::start() { 31 void cacicD::start() {
25 try{ 32 try{
26 - this->app = application();  
27 - QLogger::QLoggerManager::get  
28 - qDebug() << "\nServiço iniciado em" << app->applicationDirPath();  
29 - QJsonObject result = ccacic->getJsonFromFile(app->applicationDirPath() + "/getConfig.json"); 33 + qDebug() << "Inicio do daemon";
  34 +
  35 + qDebug() << "\nServiço iniciado em" << application()->applicationDirPath();
  36 + QLogger::QLog_Info("Cacic Daemon", QString("Servico iniciado em ").append(application()->applicationDirPath()).append("."));
  37 +
  38 + QJsonObject result = ccacic->getJsonFromFile(application()->applicationDirPath() + "/getConfig.json");
  39 +
30 if(!result.contains("error") && !result.isEmpty()){ 40 if(!result.contains("error") && !result.isEmpty()){
31 - Ocacictimer->iniciarTimer(result["codestatus"].toInt(), app->applicationDirPath()); 41 + Ocacictimer->iniciarTimer(result["codestatus"].toInt(), application()->applicationDirPath());
32 }else{ 42 }else{
33 qDebug() << "getConfig.json não encontrado."; 43 qDebug() << "getConfig.json não encontrado.";
34 } 44 }
  45 +
  46 + QLogger::QLog_Info("Cacic Daemon", "Serviço finalizado.");
35 }catch (...){ 47 }catch (...){
36 qCritical() << "Error desconhecido ao iniciar o serviço."; 48 qCritical() << "Error desconhecido ao iniciar o serviço.";
37 } 49 }
cacic-daemon/cacicD/cacicd.h
1 #ifndef CACICD_H 1 #ifndef CACICD_H
2 #define CACICD_H 2 #define CACICD_H
3 #include <QCoreApplication> 3 #include <QCoreApplication>
  4 +#include <QEventLoop>
4 #include "qtservice.h" 5 #include "qtservice.h"
5 #include "cacictimer.h" 6 #include "cacictimer.h"
  7 +#include "QLogger.h"
  8 +
6 9
7 class cacicD : public QtService<QCoreApplication> 10 class cacicD : public QtService<QCoreApplication>
8 { 11 {
9 public: 12 public:
10 - QCoreApplication *app; 13 +// QCoreApplication *app;
  14 + QLogger::QLoggerManager *logManager;
11 CacicTimer *Ocacictimer; 15 CacicTimer *Ocacictimer;
12 CCacic *ccacic; 16 CCacic *ccacic;
13 cacicD(int argc, char **argv); 17 cacicD(int argc, char **argv);
14 ~cacicD(); 18 ~cacicD();
  19 +
15 void start(); 20 void start();
16 void pause(); 21 void pause();
17 void resume(); 22 void resume();
18 void stop(); 23 void stop();
  24 +
  25 +private:
  26 +
19 }; 27 };
20 #endif // CACICD_H 28 #endif // CACICD_H
cacic-daemon/cacicD/cacictimer.cpp
@@ -5,14 +5,15 @@ CacicTimer::CacicTimer() @@ -5,14 +5,15 @@ CacicTimer::CacicTimer()
5 OCacicComm = new CacicComm(); 5 OCacicComm = new CacicComm();
6 ccacic = new CCacic(); 6 ccacic = new CCacic();
7 timer = new QTimer(this); 7 timer = new QTimer(this);
8 - //manager = QLogger::QLoggerManager::getInstance();  
9 - //manager->addDestination("cacicLog.txt", QStringList("CacicD"), QLogger::LogLevel); 8 + logManager = QLogger::QLoggerManager::getInstance();
10 connect(timer,SIGNAL(timeout()),this,SLOT(mslot())); 9 connect(timer,SIGNAL(timeout()),this,SLOT(mslot()));
11 } 10 }
12 11
13 void CacicTimer::iniciarTimer(int x, QString applicationDirPath) 12 void CacicTimer::iniciarTimer(int x, QString applicationDirPath)
14 { 13 {
15 setApplicationDirPath(applicationDirPath); 14 setApplicationDirPath(applicationDirPath);
  15 + logManager->addDestination(getApplicationDirPath().append("/cacicLog.txt"), QStringList("Cacic Daemon"), QLogger::InfoLevel);
  16 + logManager->addDestination(getApplicationDirPath().append("/cacicLog.txt"), QStringList("Cacic Daemon"), QLogger::ErrorLevel);
16 timer->start(x); 17 timer->start(x);
17 } 18 }
18 19
@@ -21,14 +22,51 @@ void CacicTimer::mslot(){ @@ -21,14 +22,51 @@ void CacicTimer::mslot(){
21 //manager->QLogger::QLog_Trace("ModuleName", "Message: "); 22 //manager->QLogger::QLog_Trace("ModuleName", "Message: ");
22 if(getConfig()){ 23 if(getConfig()){
23 qDebug() << "getConfig() success. - " + QDateTime::currentDateTime().toLocalTime().toString(); 24 qDebug() << "getConfig() success. - " + QDateTime::currentDateTime().toLocalTime().toString();
  25 + QLogger::QLog_Info("Cacic Daemon", "getConfig() executado com sucesso.");
  26 +
  27 + // Compara o novo arquivo de configuração com um antigo e se forem diferentes
  28 + // mantem o mais recente; caso iguais simplesmente apaga o novo.
  29 + QFile *fileConfig = new QFile(getApplicationDirPath().append("/getConfig.json"));
  30 + QFile *fileConfigNew = new QFile(getApplicationDirPath().append("/getConfigNew.json"));
  31 +
  32 + if( fileConfig->exists() && fileConfigNew->exists() ){
  33 + if( Md5IsEqual(QVariant::fromValue(fileConfig), QVariant::fromValue(fileConfigNew)) ) {
  34 + fileConfigNew->remove();
  35 + delete fileConfigNew;
  36 + } else {
  37 + // Renomeia getConfigNew.json para getConfig.json
  38 + fileConfig->remove();
  39 + delete fileConfig;
  40 + fileConfigNew->rename("getConfigNew.json","getConfig.json");
  41 + delete fileConfigNew;
  42 + }
  43 + jsonConfig = ccacic->getJsonFromFile(getApplicationDirPath().append("/getConfig.json"));
  44 + } else if( fileConfig->exists() ){
  45 + jsonConfig = ccacic->getJsonFromFile(getApplicationDirPath().append("/getConfig.json"));
  46 + } else {
  47 + QLogger::QLog_Error("Cacic Daemon", "Arquivo de configuração não criado.");
  48 + }
  49 +
  50 + /* lê json de configurações e armazena quais módulos executáveis.
  51 + * E faz o mesmo tipo de comparação de hashs, com o fim de:
  52 + * ou mantem o binário do módulo ou baixa um novo.
  53 + */
  54 + foreach( QVariant vectorsContent, jsonConfig["modulos"].toArray().toVariantList().toVector() )
  55 + moduleList.append( vectorsContent.toString() );
  56 +
  57 + foreach( QString modulo, moduleList ) {
  58 +
  59 + }
24 60
25 //aqui irá abrir o semaforo e iniciar a coleta. 61 //aqui irá abrir o semaforo e iniciar a coleta.
26 62
27 }else{ 63 }else{
28 qDebug() << "getConfig() failed. - " + QDateTime::currentDateTime().toLocalTime().toString(); 64 qDebug() << "getConfig() failed. - " + QDateTime::currentDateTime().toLocalTime().toString();
  65 + QLogger::QLog_Error("Cacic Daemon", "Falha na obtenção do arquivo de configuração.");
29 } 66 }
30 }else{ 67 }else{
31 qDebug() << "getTest() failed. - " + QDateTime::currentDateTime().toLocalTime().toString(); 68 qDebug() << "getTest() failed. - " + QDateTime::currentDateTime().toLocalTime().toString();
  69 + QLogger::QLog_Error("Cacic Daemon", "Falha na execução do getTest().");
32 } 70 }
33 } 71 }
34 72
@@ -70,7 +108,7 @@ bool CacicTimer::getConfig(){ @@ -70,7 +108,7 @@ bool CacicTimer::getConfig(){
70 return false; 108 return false;
71 } 109 }
72 try{ 110 try{
73 - ccacic->setJsonToFile(jsonresult, getApplicationDirPath() + "/getConfig.json"); 111 + ccacic->setJsonToFile(jsonresult, getApplicationDirPath().append("/getConfigNew.json"));
74 return true; 112 return true;
75 } catch (...) { 113 } catch (...) {
76 qDebug() << "Erro ao salvar o arquivo de configurações."; 114 qDebug() << "Erro ao salvar o arquivo de configurações.";
@@ -101,11 +139,11 @@ void CacicTimer::registraFim() @@ -101,11 +139,11 @@ void CacicTimer::registraFim()
101 { 139 {
102 } 140 }
103 141
104 -bool CacicTimer::compararHashMD5(QJsonDocument getconfigfile,QJsonDocument getConfig){ 142 +bool CacicTimer::Md5IsEqual(QVariant document01,QVariant document02){
105 QString getconfigMD5 = QString(QCryptographicHash::hash( 143 QString getconfigMD5 = QString(QCryptographicHash::hash(
106 - (getconfigfile.toVariant().toByteArray()),QCryptographicHash::Md5).toHex()); 144 + (document01.toByteArray()),QCryptographicHash::Md5).toHex());
107 QString getconfigMD52 = QString(QCryptographicHash::hash( 145 QString getconfigMD52 = QString(QCryptographicHash::hash(
108 - (getConfig.toVariant().toByteArray()),QCryptographicHash::Md5).toHex()); 146 + (document02.toByteArray()),QCryptographicHash::Md5).toHex());
109 if(getconfigMD5 == getconfigMD52){ 147 if(getconfigMD5 == getconfigMD52){
110 return true; 148 return true;
111 }else{ 149 }else{
cacic-daemon/cacicD/cacictimer.h
@@ -23,14 +23,18 @@ public: @@ -23,14 +23,18 @@ public:
23 void iniciarTimer(int x, QString applicationDirPath); 23 void iniciarTimer(int x, QString applicationDirPath);
24 bool getTest(); 24 bool getTest();
25 bool getConfig(); 25 bool getConfig();
26 - bool compararHashMD5(QJsonDocument getconfigfile,QJsonDocument getConfig); 26 + bool Md5IsEqual(QVariant document01,QVariant document02);
27 QString getApplicationDirPath() const; 27 QString getApplicationDirPath() const;
28 void setApplicationDirPath(const QString &value); 28 void setApplicationDirPath(const QString &value);
29 29
30 private: 30 private:
31 void registraFim(); 31 void registraFim();
32 void registraInicio(); 32 void registraInicio();
  33 +
  34 + QJsonObject jsonConfig;
  35 + QLogger::QLoggerManager *logManager;
33 QString applicationDirPath; 36 QString applicationDirPath;
  37 + QStringList moduleList;
34 38
35 private slots: 39 private slots:
36 void mslot(); 40 void mslot();
cacic-daemon/cacicD/main.cpp
@@ -5,5 +5,6 @@ @@ -5,5 +5,6 @@
5 int main(int argc, char **argv) 5 int main(int argc, char **argv)
6 { 6 {
7 cacicD service(argc, argv); 7 cacicD service(argc, argv);
  8 +
8 return service.exec(); 9 return service.exec();
9 } 10 }
cacic-teste/testcacic.cpp
@@ -267,23 +267,67 @@ void CTestCacic::testLogger() @@ -267,23 +267,67 @@ void CTestCacic::testLogger()
267 { 267 {
268 QLogger::QLoggerManager *logManager = QLogger::QLoggerManager::getInstance(); 268 QLogger::QLoggerManager *logManager = QLogger::QLoggerManager::getInstance();
269 logManager->addDestination("./log.txt","teste",QLogger::DebugLevel); 269 logManager->addDestination("./log.txt","teste",QLogger::DebugLevel);
  270 + logManager->addDestination("log01.txt","teste01",QLogger::DebugLevel);
  271 + logManager->addDestination("./log02.txt","teste02",QLogger::DebugLevel);
  272 + logManager->addDestination("../log03.txt","teste03",QLogger::DebugLevel);
  273 + logManager->addDestination("logs/log04.txt","teste04",QLogger::DebugLevel);
  274 + logManager->addDestination("./logs/log05.txt","teste05",QLogger::DebugLevel);
  275 + logManager->addDestination("../logs/log06.txt","teste06",QLogger::DebugLevel);
  276 +
  277 + QLogger::QLog_Debug("teste01", "Teste do modulo logger.");
  278 + QLogger::QLog_Debug("teste02", "Teste do modulo logger.");
  279 + QLogger::QLog_Debug("teste03", "Teste do modulo logger.");
  280 + QLogger::QLog_Debug("teste04", "Teste do modulo logger.");
  281 + QLogger::QLog_Debug("teste05", "Teste do modulo logger.");
  282 + QLogger::QLog_Debug("teste06", "Teste do modulo logger.");
  283 +
  284 + QFile logFile01("log01.txt");
  285 + if(logFile01.exists()) logFile01.open(QIODevice::ReadOnly);
  286 + QFile logFile02("./log02.txt");
  287 + if(logFile02.exists()) logFile02.open(QIODevice::ReadOnly);
  288 + QFile logFile03("../log03.txt");
  289 + if(logFile03.exists()) logFile03.open(QIODevice::ReadOnly);
  290 + QFile logFile04("logs/log04.txt");
  291 + if(logFile04.exists()) logFile04.open(QIODevice::ReadOnly);
  292 + QFile logFile05("./logs/log05.txt");
  293 + if(logFile05.exists()) logFile05.open(QIODevice::ReadOnly);
  294 + QFile logFile06("../logs/log06.txt");
  295 + if(logFile06.exists()) logFile06.open(QIODevice::ReadOnly);
270 296
271 - QLogger::QLog_Debug("teste", "Teste do módulo logger.");  
272 -  
273 - QFile logFile("./log.txt");  
274 - if(logFile.exists()) logFile.open(QIODevice::ReadOnly);  
275 QVERIFY(logManager && 297 QVERIFY(logManager &&
276 - logFile.exists() &&  
277 - logFile.readLine().contains("Teste") 298 + logFile01.exists() &&
  299 + logFile01.readLine().contains("Teste do modulo logger.") &&
  300 + logFile02.exists() &&
  301 + logFile02.readLine().contains("Teste do modulo logger.") &&
  302 + logFile03.exists() &&
  303 + logFile03.readLine().contains("Teste do modulo logger.") &&
  304 + logFile04.exists() &&
  305 + logFile04.readLine().contains("Teste do modulo logger.") &&
  306 + logFile05.exists() &&
  307 + logFile05.readLine().contains("Teste do modulo logger.") &&
  308 + logFile06.exists() &&
  309 + logFile06.readLine().contains("Teste do modulo logger.")
278 ); 310 );
279 311
280 logManager->closeLogger(); 312 logManager->closeLogger();
281 - logFile.close(); 313 + logFile01.close();
  314 + logFile02.close();
  315 + logFile03.close();
  316 + logFile04.close();
  317 + logFile05.close();
  318 + logFile06.close();
282 } 319 }
283 320
284 void CTestCacic::cleanupTestCase() 321 void CTestCacic::cleanupTestCase()
285 { 322 {
286 - OCacic.deleteFile("log.txt"); 323 + OCacic.deleteFile("log01.txt");
  324 + OCacic.deleteFile("./log02.txt");
  325 + OCacic.deleteFile("../log03.txt");
  326 + OCacic.deleteFile("logs/log04.txt");
  327 + OCacic.deleteFile("./logs/log05.txt");
  328 + OCacic.deleteFolder("./logs");
  329 + OCacic.deleteFile("../logs/log06.txt");
  330 + OCacic.deleteFolder("../logs");
287 OCacic.deleteFile("configRequest.json"); 331 OCacic.deleteFile("configRequest.json");
288 OCacic.deleteFile("teste.json"); 332 OCacic.deleteFile("teste.json");
289 OCacic.deleteFile("configReq.json"); 333 OCacic.deleteFile("configReq.json");
install-cacic/install-cacic.pro
@@ -7,7 +7,6 @@ @@ -7,7 +7,6 @@
7 QT += core 7 QT += core
8 QT += network 8 QT += network
9 QT -= gui 9 QT -= gui
10 -QT += axcontainer  
11 10
12 TARGET = install-cacic 11 TARGET = install-cacic
13 CONFIG += console 12 CONFIG += console
@@ -16,6 +15,7 @@ CONFIG += c++11 @@ -16,6 +15,7 @@ CONFIG += c++11
16 15
17 win32 { 16 win32 {
18 LIBS += -LE:\LightBase\cacic-agente-project\cacic-agente\src\crypto++\lib -lcryptopp 17 LIBS += -LE:\LightBase\cacic-agente-project\cacic-agente\src\crypto++\lib -lcryptopp
  18 + QT += axcontainer
19 } else { 19 } else {
20 LIBS += -L/usr/lib -lcryptopp 20 LIBS += -L/usr/lib -lcryptopp
21 } 21 }
@@ -27,7 +27,8 @@ SOURCES += main.cpp \ @@ -27,7 +27,8 @@ SOURCES += main.cpp \
27 ../src/ccacic.cpp \ 27 ../src/ccacic.cpp \
28 ../src/cacic_computer.cpp \ 28 ../src/cacic_computer.cpp \
29 ../src/operatingsystem.cpp \ 29 ../src/operatingsystem.cpp \
30 - ../src/wmi.cpp 30 + ../src/wmi.cpp \
  31 + ../src/QLogger.cpp
31 32
32 HEADERS += \ 33 HEADERS += \
33 installcacic.h \ 34 installcacic.h \
@@ -35,7 +36,8 @@ HEADERS += \ @@ -35,7 +36,8 @@ HEADERS += \
35 ../src/cacic_computer.h \ 36 ../src/cacic_computer.h \
36 ../src/cacic_comm.h \ 37 ../src/cacic_comm.h \
37 ../src/operatingsystem.h \ 38 ../src/operatingsystem.h \
38 - ../src/wmi.h 39 + ../src/wmi.h \
  40 + ../src/QLogger.h
39 41
40 INCLUDEPATH += ../src \ 42 INCLUDEPATH += ../src \
41 ../src/crypto++/include/ 43 ../src/crypto++/include/
install-cacic/installcacic.cpp
@@ -3,10 +3,13 @@ @@ -3,10 +3,13 @@
3 InstallCacic::InstallCacic(QObject *parent) : 3 InstallCacic::InstallCacic(QObject *parent) :
4 QObject(parent) 4 QObject(parent)
5 { 5 {
6 - 6 + logManager = QLogger::QLoggerManager::getInstance();
  7 + logManager->addDestination("./log.txt","Install",QLogger::DebugLevel);
7 } 8 }
8 9
9 void InstallCacic::run(QStringList argv, int argc) { 10 void InstallCacic::run(QStringList argv, int argc) {
  11 +
  12 + QLogger::QLog_Debug("Install", "Inicio de instalacao");
10 bool ok; 13 bool ok;
11 //valida os parametros repassados 14 //valida os parametros repassados
12 QMap<QString, QString> param = validaParametros(argv, argc, &ok); 15 QMap<QString, QString> param = validaParametros(argv, argc, &ok);
@@ -21,8 +24,8 @@ void InstallCacic::run(QStringList argv, int argc) { @@ -21,8 +24,8 @@ void InstallCacic::run(QStringList argv, int argc) {
21 oCacic.setChaveCrypt(jsonLogin["reply"].toObject()["chavecrip"].toString()); 24 oCacic.setChaveCrypt(jsonLogin["reply"].toObject()["chavecrip"].toString());
22 #ifdef Q_OS_WIN 25 #ifdef Q_OS_WIN
23 oCacic.setCacicMainFolder("c:/cacic/"); 26 oCacic.setCacicMainFolder("c:/cacic/");
24 -#elif Q_LINUX  
25 - oCacic.setCacicMainFolder("/home/cacic/"); 27 +#elif defined(Q_OS_LINUX)
  28 + oCacic.setCacicMainFolder("/home/cacic");
26 #endif 29 #endif
27 oCacic.createFolder(oCacic.getCacicMainFolder()); 30 oCacic.createFolder(oCacic.getCacicMainFolder());
28 //grava chave em registro; 31 //grava chave em registro;
@@ -59,6 +62,7 @@ void InstallCacic::run(QStringList argv, int argc) { @@ -59,6 +62,7 @@ void InstallCacic::run(QStringList argv, int argc) {
59 << " [-help] Lista todos comandos.\n"; 62 << " [-help] Lista todos comandos.\n";
60 } 63 }
61 64
  65 + logManager->closeLogger();
62 emit finished(); 66 emit finished();
63 } 67 }
64 68
install-cacic/installcacic.h
@@ -7,6 +7,7 @@ @@ -7,6 +7,7 @@
7 #include <cacic_computer.h> 7 #include <cacic_computer.h>
8 #include <ccacic.h> 8 #include <ccacic.h>
9 #include "iostream" 9 #include "iostream"
  10 +#include "QLogger.h"
10 11
11 class InstallCacic : public QObject 12 class InstallCacic : public QObject
12 { 13 {
@@ -25,6 +26,7 @@ private: @@ -25,6 +26,7 @@ private:
25 CacicComm oCacicComm; 26 CacicComm oCacicComm;
26 CACIC_Computer oCacicComputer; 27 CACIC_Computer oCacicComputer;
27 CCacic oCacic; 28 CCacic oCacic;
  29 + QLogger::QLoggerManager *logManager;
28 signals: 30 signals:
29 void finished(); 31 void finished();
30 32
src/QLogger.cpp
@@ -113,6 +113,7 @@ namespace QLogger @@ -113,6 +113,7 @@ namespace QLogger
113 bool QLoggerManager::addDestination(const QString &fileDest, const QStringList &modules, LogLevel level) 113 bool QLoggerManager::addDestination(const QString &fileDest, const QStringList &modules, LogLevel level)
114 { 114 {
115 QLoggerWriter *log; 115 QLoggerWriter *log;
  116 +
116 foreach (QString module, modules) 117 foreach (QString module, modules)
117 { 118 {
118 if (!moduleDest.contains(module)) 119 if (!moduleDest.contains(module))
@@ -139,13 +140,31 @@ namespace QLogger @@ -139,13 +140,31 @@ namespace QLogger
139 140
140 void QLoggerWriter::write(const QString &module, const QString &message) 141 void QLoggerWriter::write(const QString &module, const QString &message)
141 { 142 {
  143 +
142 QString _fileName = m_fileDestination; 144 QString _fileName = m_fileDestination;
  145 + QStringList fileDestSplit;
  146 + QString dirDest;
143 147
144 int MAX_SIZE = 1024 * 1024; 148 int MAX_SIZE = 1024 * 1024;
145 149
146 - QDir dir(QDir::currentPath());  
147 - if (!dir.exists("logs"))  
148 - dir.mkdir("logs"); 150 + if (_fileName.contains("/"))
  151 + {
  152 + fileDestSplit = _fileName.split("/");
  153 +
  154 + for(int i = 0 ; i < fileDestSplit.size() ; ++i )
  155 + {
  156 + if( !(i == fileDestSplit.size() - 1) ) // last fileDestSplit element
  157 + {
  158 + dirDest.append(fileDestSplit[i] + "/");
  159 + }
  160 + }
  161 +
  162 +
  163 + QDir dir(QDir::currentPath());
  164 +
  165 + if (!dir.exists(dirDest))
  166 + dir.mkdir(dirDest);
  167 + }
149 168
150 QFile file(_fileName); 169 QFile file(_fileName);
151 QString toRemove = _fileName.section('.',-1); 170 QString toRemove = _fileName.section('.',-1);
@@ -153,10 +172,10 @@ namespace QLogger @@ -153,10 +172,10 @@ namespace QLogger
153 bool renamed = false; 172 bool renamed = false;
154 QString newName = fileNameAux + "_%1__%2.log"; 173 QString newName = fileNameAux + "_%1__%2.log";
155 174
156 - //Renomenem l'arxiu si està ple 175 + //Renomeia o arquivo se ele está cheio
157 if (file.size() >= MAX_SIZE) 176 if (file.size() >= MAX_SIZE)
158 { 177 {
159 - //Creem un fixer nou 178 + //Cria um novo arquivo
160 QDateTime currentTime = QDateTime::currentDateTime(); 179 QDateTime currentTime = QDateTime::currentDateTime();
161 newName = newName.arg(currentTime.date().toString("dd_MM_yy")).arg(currentTime.time().toString("hh_mm_ss")); 180 newName = newName.arg(currentTime.date().toString("dd_MM_yy")).arg(currentTime.time().toString("hh_mm_ss"));
162 renamed = file.rename(_fileName, newName); 181 renamed = file.rename(_fileName, newName);
@@ -166,6 +185,7 @@ namespace QLogger @@ -166,6 +185,7 @@ namespace QLogger
166 file.setFileName(_fileName); 185 file.setFileName(_fileName);
167 if (file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append)) 186 if (file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append))
168 { 187 {
  188 +
169 QTextStream out(&file); 189 QTextStream out(&file);
170 QString dtFormat = QDateTime::currentDateTime().toString("dd-MM-yyyy hh:mm:ss.zzz"); 190 QString dtFormat = QDateTime::currentDateTime().toString("dd-MM-yyyy hh:mm:ss.zzz");
171 191
@@ -174,8 +194,12 @@ namespace QLogger @@ -174,8 +194,12 @@ namespace QLogger
174 194
175 QString logLevel = QLoggerManager::levelToText(m_level); 195 QString logLevel = QLoggerManager::levelToText(m_level);
176 QString text = QString("[%1] [%2] {%3} %4\n").arg(dtFormat).arg(logLevel).arg(module).arg(message); 196 QString text = QString("[%1] [%2] {%3} %4\n").arg(dtFormat).arg(logLevel).arg(module).arg(message);
  197 +
177 out << text; 198 out << text;
  199 +
178 file.close(); 200 file.close();
  201 + } else {
  202 + qWarning() << "Não foi possível abrir arquivo de log.";
179 } 203 }
180 } 204 }
181 } 205 }
@@ -25,6 +25,7 @@ @@ -25,6 +25,7 @@
25 #include <QMap> 25 #include <QMap>
26 #include <QThread> 26 #include <QThread>
27 #include <QMutex> 27 #include <QMutex>
  28 +#include <QDebug>
28 29
29 /**************************************************************************************************/ 30 /**************************************************************************************************/
30 /*** GENERAL USAGE ***/ 31 /*** GENERAL USAGE ***/