diff --git a/rbutil/rbutilqt/base/autodetection.cpp b/rbutil/rbutilqt/base/autodetection.cpp index 4b3d1a1ab1..1253202e40 100644 --- a/rbutil/rbutilqt/base/autodetection.cpp +++ b/rbutil/rbutilqt/base/autodetection.cpp @@ -28,6 +28,7 @@ #include "system.h" #include "utils.h" #include "rockboxinfo.h" +#include "Logger.h" Autodetection::Autodetection(QObject* parent): QObject(parent) { @@ -67,8 +68,8 @@ bool Autodetection::detect(void) } } for(int i = 0; i < m_detected.size(); ++i) { - qDebug() << "[Autodetect] Detected player:" << m_detected.at(i).device - << "at" << m_detected.at(i).mountpoint << states[m_detected.at(i).status]; + LOG_INFO() << "Detected player:" << m_detected.at(i).device + << "at" << m_detected.at(i).mountpoint << states[m_detected.at(i).status]; } return m_detected.size() > 0; @@ -98,14 +99,14 @@ void Autodetection::detectUsb() d.status = PlayerOk; d.usbdevices = usbids.value(attached.at(i)); m_detected.append(d); - qDebug() << "[USB] detected supported player" << d.usbdevices; + LOG_INFO() << "[USB] detected supported player" << d.usbdevices; } if(usberror.contains(attached.at(i))) { struct Detected d; d.status = PlayerMtpMode; d.device = usbids.value(attached.at(i)).at(0); m_detected.append(d); - qDebug() << "[USB] detected problem with player" << d.device; + LOG_WARNING() << "[USB] detected problem with player" << d.device; } QString idstring = QString("%1").arg(attached.at(i), 8, 16, QChar('0')); if(!SystemInfo::platformValue(idstring, SystemInfo::CurName).toString().isEmpty()) { @@ -113,7 +114,7 @@ void Autodetection::detectUsb() d.status = PlayerIncompatible; d.device = idstring; m_detected.append(d); - qDebug() << "[USB] detected incompatible player" << d.device; + LOG_WARNING() << "[USB] detected incompatible player" << d.device; } } } @@ -125,7 +126,7 @@ void Autodetection::detectUsb() void Autodetection::mergeMounted(void) { QStringList mounts = Utils::mountpoints(Utils::MountpointsSupported); - qDebug() << "[Autodetect] paths to check:" << mounts; + LOG_INFO() << "paths to check:" << mounts; for(int i = 0; i < mounts.size(); i++) { @@ -143,8 +144,8 @@ void Autodetection::mergeMounted(void) d.mountpoint = mounts.at(i); d.status = PlayerOk; updateDetectedDevice(d); - qDebug() << "[Autodetect] rbutil.log detected:" - << log.value("platform").toString() << mounts.at(i); + LOG_INFO() << "rbutil.log detected:" + << log.value("platform").toString() << mounts.at(i); } } @@ -157,8 +158,8 @@ void Autodetection::mergeMounted(void) d.mountpoint = mounts.at(i); d.status = PlayerOk; updateDetectedDevice(d); - qDebug() << "[Autodetect] rockbox-info.txt detected:" - << info.target() << mounts.at(i); + LOG_INFO() << "rockbox-info.txt detected:" + << info.target() << mounts.at(i); } // check for some specific files in root folder @@ -193,13 +194,13 @@ void Autodetection::mergeMounted(void) } if(rootentries.contains("ajbrec.ajz", Qt::CaseInsensitive)) { - qDebug() << "[Autodetect] ajbrec.ajz found. Trying detectAjbrec()"; + LOG_INFO() << "ajbrec.ajz found. Trying detectAjbrec()"; struct Detected d; d.device = detectAjbrec(mounts.at(i)); d.mountpoint = mounts.at(i); d.status = PlayerOk; if(!d.device.isEmpty()) { - qDebug() << "[Autodetect]" << d.device; + LOG_INFO() << d.device; updateDetectedDevice(d); } } @@ -255,7 +256,7 @@ void Autodetection::mergePatcher(void) n = ipod_scan(&ipod); // FIXME: handle more than one Ipod connected in ipodpatcher. if(n == 1) { - qDebug() << "[Autodetect] Ipod found:" << ipod.modelstr << "at" << ipod.diskname; + LOG_INFO() << "Ipod found:" << ipod.modelstr << "at" << ipod.diskname; // since resolveMountPoint is doing exact matches we need to select // the correct partition. QString mp(ipod.diskname); @@ -276,7 +277,7 @@ void Autodetection::mergePatcher(void) updateDetectedDevice(d); } else { - qDebug() << "[Autodetect] ipodpatcher: no Ipod found." << n; + LOG_INFO() << "ipodpatcher: no Ipod found." << n; } ipod_dealloc_buffer(&ipod); @@ -286,8 +287,8 @@ void Autodetection::mergePatcher(void) sansa_alloc_buffer(&sansa, BUFFER_SIZE); n = sansa_scan(&sansa); if(n == 1) { - qDebug() << "[Autodetect] Sansa found:" - << sansa.targetname << "at" << sansa.diskname; + LOG_INFO() << "Sansa found:" + << sansa.targetname << "at" << sansa.diskname; QString mp(sansa.diskname); #ifdef Q_OS_LINUX mp.append("1"); @@ -302,7 +303,7 @@ void Autodetection::mergePatcher(void) updateDetectedDevice(d); } else { - qDebug() << "[Autodetect] sansapatcher: no Sansa found." << n; + LOG_INFO() << "sansapatcher: no Sansa found." << n; } sansa_dealloc_buffer(&sansa); } @@ -323,8 +324,8 @@ QString Autodetection::detectAjbrec(QString root) // recorder v1 has the binary length in the first 4 bytes, so check // for them first. int len = (header[0]<<24) | (header[1]<<16) | (header[2]<<8) | header[3]; - qDebug() << "[Autodetect] ABJREC possible bin length:" << len - << "file len:" << f.size(); + LOG_INFO() << "abjrec.ajz possible bin length:" << len + << "file len:" << f.size(); if((f.size() - 6) == len) return "recorder"; diff --git a/rbutil/rbutilqt/base/bootloaderinstallams.cpp b/rbutil/rbutilqt/base/bootloaderinstallams.cpp index dbdac8e2ce..33ad51c200 100644 --- a/rbutil/rbutilqt/base/bootloaderinstallams.cpp +++ b/rbutil/rbutilqt/base/bootloaderinstallams.cpp @@ -19,6 +19,7 @@ #include #include "bootloaderinstallbase.h" #include "bootloaderinstallams.h" +#include "Logger.h" #include "../mkamsboot/mkamsboot.h" @@ -51,7 +52,7 @@ bool BootloaderInstallAms::install(void) if(m_offile.isEmpty()) return false; - qDebug() << "[BootloaderInstallAms] installing bootloader"; + LOG_INFO() << "installing bootloader"; // download firmware from server emit logItem(tr("Downloading bootloader file"), LOGINFO); @@ -64,7 +65,7 @@ bool BootloaderInstallAms::install(void) void BootloaderInstallAms::installStage2(void) { - qDebug() << "[BootloaderInstallAms] installStage2"; + LOG_INFO() << "installStage2"; unsigned char* buf; unsigned char* of_packed; @@ -94,7 +95,7 @@ void BootloaderInstallAms::installStage2(void) errstr,sizeof(errstr)); if (rb_packed == NULL) { - qDebug() << "[BootloaderInstallAms] could not load bootloader: " << bootfile; + LOG_ERROR() << "could not load bootloader: " << bootfile; emit logItem(errstr, LOGERROR); emit logItem(tr("Could not load %1").arg(bootfile), LOGERROR); emit done(true); @@ -107,7 +108,7 @@ void BootloaderInstallAms::installStage2(void) errstr, sizeof(errstr)); if (buf == NULL) { - qDebug() << "[BootloaderInstallAms] could not load OF: " << m_offile; + LOG_ERROR() << "could not load OF: " << m_offile; emit logItem(errstr, LOGERROR); emit logItem(tr("Could not load %1").arg(m_offile), LOGERROR); free(rb_packed); @@ -121,7 +122,7 @@ void BootloaderInstallAms::installStage2(void) if (!patchable) { - qDebug() << "[BootloaderInstallAms] No room to insert bootloader"; + LOG_ERROR() << "No room to insert bootloader"; emit logItem(errstr, LOGERROR); emit logItem(tr("No room to insert bootloader, try another firmware version"), LOGERROR); @@ -143,7 +144,7 @@ void BootloaderInstallAms::installStage2(void) if(!out.open(QIODevice::WriteOnly | QIODevice::Truncate)) { - qDebug() << "[BootloaderInstallAms] Could not open" << m_blfile << "for writing"; + LOG_ERROR() << "Could not open" << m_blfile << "for writing"; emit logItem(tr("Could not open %1 for writing").arg(m_blfile),LOGERROR); free(buf); free(of_packed); @@ -156,7 +157,7 @@ void BootloaderInstallAms::installStage2(void) if (n != len) { - qDebug() << "[BootloaderInstallAms] Could not write firmware file"; + LOG_ERROR() << "Could not write firmware file"; emit logItem(tr("Could not write firmware file"),LOGERROR); free(buf); free(of_packed); @@ -172,7 +173,7 @@ void BootloaderInstallAms::installStage2(void) free(rb_packed); //end of install - qDebug() << "[BootloaderInstallAms] install successfull"; + LOG_INFO() << "install successfull"; emit logItem(tr("Success: modified firmware file created"), LOGINFO); logInstall(LogAdd); emit done(false); diff --git a/rbutil/rbutilqt/base/bootloaderinstallbase.cpp b/rbutil/rbutilqt/base/bootloaderinstallbase.cpp index 1a47f967b0..9a1c74c690 100644 --- a/rbutil/rbutilqt/base/bootloaderinstallbase.cpp +++ b/rbutil/rbutilqt/base/bootloaderinstallbase.cpp @@ -23,6 +23,7 @@ #include "utils.h" #include "ziputil.h" #include "mspackutil.h" +#include "Logger.h" #if defined(Q_OS_MACX) #include @@ -58,8 +59,8 @@ void BootloaderInstallBase::downloadBlStart(QUrl source) void BootloaderInstallBase::downloadReqFinished(int id, bool error) { - qDebug() << "[BootloaderInstallBase] Download Request" << id - << "finished, error:" << m_http.errorString(); + LOG_INFO() << "Download Request" << id + << "finished, error:" << m_http.errorString(); downloadBlFinish(error); } @@ -67,8 +68,8 @@ void BootloaderInstallBase::downloadReqFinished(int id, bool error) void BootloaderInstallBase::downloadBlFinish(bool error) { - qDebug() << "[BootloaderInstallBase] Downloading bootloader finished, error:" - << error; + LOG_INFO() << "Downloading bootloader finished, error:" + << error; // update progress bar emit logProgress(100, 100); @@ -98,7 +99,7 @@ void BootloaderInstallBase::downloadBlFinish(bool error) void BootloaderInstallBase::installBlfile(void) { - qDebug() << "[BootloaderInstallBase] installBlFile(void)"; + LOG_INFO() << "installBlFile(void)"; } @@ -107,7 +108,7 @@ void BootloaderInstallBase::installBlfile(void) //! @return true on success, false on error. bool BootloaderInstallBase::backup(QString to) { - qDebug() << "[BootloaderInstallBase] Backing up bootloader file"; + LOG_INFO() << "Backing up bootloader file"; QDir targetDir("."); emit logItem(tr("Creating backup of original firmware file."), LOGINFO); if(!targetDir.mkpath(to)) { @@ -115,7 +116,7 @@ bool BootloaderInstallBase::backup(QString to) return false; } QString tofile = to + "/" + QFileInfo(m_blfile).fileName(); - qDebug() << "[BootloaderInstallBase] trying to backup" << m_blfile << "to" << tofile; + LOG_INFO() << "trying to backup" << m_blfile << "to" << tofile; if(!QFile::copy(Utils::resolvePathCase(m_blfile), tofile)) { emit logItem(tr("Creating backup copy failed."), LOGERROR); return false; @@ -137,8 +138,8 @@ int BootloaderInstallBase::logInstall(LogMode mode) if(mode == LogAdd) { s.setValue("Bootloader/" + section, m_blversion.toString(Qt::ISODate)); - qDebug() << "[BootloaderInstallBase] Writing log, version:" - << m_blversion.toString(Qt::ISODate); + LOG_INFO() << "Writing log, version:" + << m_blversion.toString(Qt::ISODate); } else { s.remove("Bootloader/" + section); @@ -182,7 +183,7 @@ void BootloaderInstallBase::checkRemount() if(!status) { // still not remounted, restart timer. QTimer::singleShot(500, this, SLOT(checkRemount())); - qDebug() << "[BootloaderInstallBase] Player not remounted yet" << m_remountDevice; + LOG_INFO() << "Player not remounted yet" << m_remountDevice; } else { emit logItem(tr("Player remounted"), LOGINFO); @@ -244,11 +245,11 @@ bool BootloaderInstallBase::setOfFile(QString of, QStringList blfile) // check if the file set is in zip format if(util) { QStringList contents = util->files(); - qDebug() << "[BootloaderInstallBase] archive contains:" << contents; + LOG_INFO() << "archive contains:" << contents; for(int i = 0; i < blfile.size(); ++i) { // strip any path, we don't know the structure in the zip QString f = QFileInfo(blfile.at(i)).fileName(); - qDebug() << "[BootloaderInstallBase] searching archive for" << f; + LOG_INFO() << "searching archive for" << f; // contents.indexOf() works case sensitive. Since the filename // casing is unknown (and might change) do this manually. // FIXME: support files in folders diff --git a/rbutil/rbutilqt/base/bootloaderinstallfile.cpp b/rbutil/rbutilqt/base/bootloaderinstallfile.cpp index fc293e54eb..70867b8868 100644 --- a/rbutil/rbutilqt/base/bootloaderinstallfile.cpp +++ b/rbutil/rbutilqt/base/bootloaderinstallfile.cpp @@ -20,6 +20,7 @@ #include #include "bootloaderinstallfile.h" #include "utils.h" +#include "Logger.h" BootloaderInstallFile::BootloaderInstallFile(QObject *parent) @@ -31,7 +32,7 @@ BootloaderInstallFile::BootloaderInstallFile(QObject *parent) bool BootloaderInstallFile::install(void) { emit logItem(tr("Downloading bootloader"), LOGINFO); - qDebug() << "[BootloaderInstallFile] installing bootloader"; + LOG_INFO() << "installing bootloader"; downloadBlStart(m_blurl); connect(this, SIGNAL(downloadDone()), this, SLOT(installStage2())); return true; @@ -46,7 +47,7 @@ void BootloaderInstallFile::installStage2(void) QString fwfile(Utils::resolvePathCase(m_blfile)); if(!fwfile.isEmpty()) { QString moved = Utils::resolvePathCase(m_blfile) + ".ORIG"; - qDebug() << "[BootloaderInstallFile] renaming" << fwfile << "to" << moved; + LOG_INFO() << "renaming" << fwfile << "to" << moved; QFile::rename(fwfile, moved); } @@ -80,8 +81,8 @@ void BootloaderInstallFile::installStage2(void) // place (new) bootloader m_tempfile.open(); - qDebug() << "[BootloaderInstallFile] renaming" << m_tempfile.fileName() - << "to" << fwfile; + LOG_INFO() << "renaming" << m_tempfile.fileName() + << "to" << fwfile; m_tempfile.close(); if(!Utils::resolvePathCase(fwfile).isEmpty()) { @@ -106,7 +107,7 @@ void BootloaderInstallFile::installStage2(void) bool BootloaderInstallFile::uninstall(void) { - qDebug() << "[BootloaderInstallFile] Uninstalling bootloader"; + LOG_INFO() << "Uninstalling bootloader"; emit logItem(tr("Removing Rockbox bootloader"), LOGINFO); // check if a .ORIG file is present, and allow moving it back. QString origbl = Utils::resolvePathCase(m_blfile + ".ORIG"); @@ -138,7 +139,7 @@ bool BootloaderInstallFile::uninstall(void) //! @return BootloaderRockbox, BootloaderOther or BootloaderUnknown. BootloaderInstallBase::BootloaderType BootloaderInstallFile::installed(void) { - qDebug() << "[BootloaderInstallFile] checking installed bootloader"; + LOG_INFO() << "checking installed bootloader"; if(!Utils::resolvePathCase(m_blfile).isEmpty() && !Utils::resolvePathCase(m_blfile + ".ORIG").isEmpty()) return BootloaderRockbox; @@ -151,7 +152,7 @@ BootloaderInstallBase::BootloaderType BootloaderInstallFile::installed(void) BootloaderInstallBase::Capabilities BootloaderInstallFile::capabilities(void) { - qDebug() << "[BootloaderInstallFile] getting capabilities"; + LOG_INFO() << "getting capabilities"; return Install | Uninstall | IsFile | CanCheckInstalled | Backup; } diff --git a/rbutil/rbutilqt/base/bootloaderinstallhex.cpp b/rbutil/rbutilqt/base/bootloaderinstallhex.cpp index 506a05522a..39a2392731 100644 --- a/rbutil/rbutilqt/base/bootloaderinstallhex.cpp +++ b/rbutil/rbutilqt/base/bootloaderinstallhex.cpp @@ -20,6 +20,7 @@ #include "bootloaderinstallbase.h" #include "bootloaderinstallhex.h" #include "utils.h" +#include "Logger.h" #include "../../tools/iriver.h" #include "../../tools/mkboot.h" @@ -74,7 +75,7 @@ bool BootloaderInstallHex::install(void) file.close(); QString hash = QCryptographicHash::hash(filedata, QCryptographicHash::Md5).toHex(); - qDebug() << "[BootloaderInstallHex] hexfile hash:" << hash; + LOG_INFO() << "hexfile hash:" << hash; if(file.error() != QFile::NoError) { emit logItem(tr("Could not verify original firmware file"), LOGERROR); emit done(true); @@ -112,7 +113,7 @@ bool BootloaderInstallHex::install(void) int result; result = iriver_decode(m_offile.toLatin1().data(), m_descrambled.fileName().toLatin1().data(), FALSE, STRIP_NONE); - qDebug() << "[BootloaderInstallHex] iriver_decode" << result; + LOG_INFO() << "iriver_decode():" << result; if(result < 0) { emit logItem(tr("Error in descramble: %1").arg(scrambleError(result)), LOGERROR); @@ -200,7 +201,7 @@ void BootloaderInstallHex::installStage2(void) targethex.close(); QString hash = QCryptographicHash::hash(filedata, QCryptographicHash::Md5).toHex(); - qDebug() << "[BootloaderInstallHex] created hexfile hash:" << hash; + LOG_INFO() << "created hexfile hash:" << hash; emit logItem(tr("Checking modified firmware file"), LOGINFO); if(hash != QString(md5sums[m_hashindex].patched)) { diff --git a/rbutil/rbutilqt/base/bootloaderinstallimx.cpp b/rbutil/rbutilqt/base/bootloaderinstallimx.cpp index e12849e856..74c6f94f78 100644 --- a/rbutil/rbutilqt/base/bootloaderinstallimx.cpp +++ b/rbutil/rbutilqt/base/bootloaderinstallimx.cpp @@ -21,6 +21,7 @@ #include "bootloaderinstallbase.h" #include "bootloaderinstallimx.h" #include "../mkimxboot/mkimxboot.h" +#include "Logger.h" // class for running mkimxboot() in a separate thread to keep the UI responsive. class BootloaderThreadImx : public QThread @@ -45,7 +46,7 @@ class BootloaderThreadImx : public QThread void BootloaderThreadImx::run(void) { - qDebug() << "[BootloaderThreadImx] Thread started."; + LOG_INFO() << "Thread started."; struct imx_option_t opt; memset(&opt, 0, sizeof(opt)); opt.debug = false; @@ -55,7 +56,7 @@ void BootloaderThreadImx::run(void) m_error = mkimxboot(m_inputfile.toLocal8Bit().constData(), m_bootfile.toLocal8Bit().constData(), m_outputfile.toLocal8Bit().constData(), opt); - qDebug() << "[BootloaderThreadImx] Thread finished, result:" << m_error; + LOG_INFO() << "Thread finished, result:" << m_error; } @@ -88,13 +89,13 @@ bool BootloaderInstallImx::install(void) { if(!QFileInfo(m_offile).isReadable()) { - qDebug() << "[BootloaderInstallImx] could not read original firmware file" + LOG_ERROR() << "could not read original firmware file" << m_offile; emit logItem(tr("Could not read original firmware file"), LOGERROR); return false; } - qDebug() << "[BootloaderInstallImx] downloading bootloader"; + LOG_INFO() << "downloading bootloader"; // download bootloader from server emit logItem(tr("Downloading bootloader file"), LOGINFO); connect(this, SIGNAL(downloadDone()), this, SLOT(installStage2())); @@ -105,7 +106,7 @@ bool BootloaderInstallImx::install(void) void BootloaderInstallImx::installStage2(void) { - qDebug() << "[BootloaderInstallImx] patching file..."; + LOG_INFO() << "patching file..."; emit logItem(tr("Patching file..."), LOGINFO); m_tempfile.open(); @@ -132,26 +133,26 @@ void BootloaderInstallImx::installStage3(void) // if the patch failed if (err != IMX_SUCCESS) { - qDebug() << "[BootloaderInstallImx] Could not patch the original firmware file"; + LOG_ERROR() << "Could not patch the original firmware file"; emit logItem(tr("Patching the original firmware failed"), LOGERROR); emit done(true); return; } - qDebug() << "[BootloaderInstallImx] Original Firmware succesfully patched"; + LOG_INFO() << "Original Firmware succesfully patched"; emit logItem(tr("Succesfully patched firmware file"), LOGINFO); // if a bootloader is already present delete it. QString fwfile(m_blfile); if(QFileInfo(fwfile).isFile()) { - qDebug() << "[BootloaderInstallImx] deleting old target file"; + LOG_INFO() << "deleting old target file"; QFile::remove(fwfile); } // place (new) bootloader. Copy, since the temporary file will be removed // automatically. - qDebug() << "[BootloaderInstallImx] moving patched bootloader to" << fwfile; + LOG_INFO() << "moving patched bootloader to" << fwfile; if(m_patchedFile.copy(fwfile)) { emit logItem(tr("Bootloader successful installed"), LOGOK); diff --git a/rbutil/rbutilqt/base/bootloaderinstallipod.cpp b/rbutil/rbutilqt/base/bootloaderinstallipod.cpp index de7aaa897b..6c23bc200f 100644 --- a/rbutil/rbutilqt/base/bootloaderinstallipod.cpp +++ b/rbutil/rbutilqt/base/bootloaderinstallipod.cpp @@ -22,6 +22,7 @@ #include "../ipodpatcher/ipodpatcher.h" #include "utils.h" +#include "Logger.h" BootloaderInstallIpod::BootloaderInstallIpod(QObject *parent) @@ -131,7 +132,8 @@ void BootloaderInstallIpod::installStage3(bool mounted) emit logItem(tr("Writing log aborted"), LOGERROR); emit done(true); } - qDebug() << "[BootloaderInstallIpod] version installed:" << m_blversion.toString(Qt::ISODate); + LOG_INFO() << "version installed:" + << m_blversion.toString(Qt::ISODate); } @@ -190,7 +192,7 @@ BootloaderInstallBase::BootloaderType BootloaderInstallIpod::installed(void) BootloaderInstallBase::BootloaderType result = BootloaderRockbox; if(!ipodInitialize(&ipod)) { - qDebug() << "[BootloaderInstallIpod] installed: BootloaderUnknown"; + LOG_INFO() << "installed: BootloaderUnknown"; result = BootloaderUnknown; } else { @@ -200,7 +202,7 @@ BootloaderInstallBase::BootloaderType BootloaderInstallIpod::installed(void) result = BootloaderOther; } else { - qDebug() << "[BootloaderInstallIpod] installed: BootloaderRockbox"; + LOG_INFO() << "installed: BootloaderRockbox"; } } ipod_close(&ipod); @@ -235,12 +237,12 @@ bool BootloaderInstallIpod::ipodInitialize(struct ipod_t *ipod) sprintf(ipod->diskname, "%s", qPrintable(devicename.remove(QRegExp("[0-9]+$")))); #endif - qDebug() << "[BootloaderInstallIpod] ipodpatcher: overriding scan, using" - << ipod->diskname; + LOG_INFO() << "ipodpatcher: overriding scan, using" + << ipod->diskname; } else { emit logItem(tr("Error: no mountpoint specified!"), LOGERROR); - qDebug() << "[BootloaderInstallIpod] no mountpoint specified!"; + LOG_ERROR() << "no mountpoint specified!"; } int result = ipod_open(ipod, 1); if(result == -2) { diff --git a/rbutil/rbutilqt/base/bootloaderinstallmi4.cpp b/rbutil/rbutilqt/base/bootloaderinstallmi4.cpp index 8bce8212a9..e4722fda23 100644 --- a/rbutil/rbutilqt/base/bootloaderinstallmi4.cpp +++ b/rbutil/rbutilqt/base/bootloaderinstallmi4.cpp @@ -21,6 +21,7 @@ #include #include "bootloaderinstallmi4.h" #include "utils.h" +#include "Logger.h" BootloaderInstallMi4::BootloaderInstallMi4(QObject *parent) : BootloaderInstallBase(parent) @@ -31,7 +32,7 @@ BootloaderInstallMi4::BootloaderInstallMi4(QObject *parent) bool BootloaderInstallMi4::install(void) { emit logItem(tr("Downloading bootloader"), LOGINFO); - qDebug() << "[BootloaderInstallMi4] installing bootloader"; + LOG_INFO() << "installing bootloader"; downloadBlStart(m_blurl); connect(this, SIGNAL(downloadDone()), this, SLOT(installStage2())); return true; @@ -48,18 +49,18 @@ void BootloaderInstallMi4::installStage2(void) QString moved = QFileInfo(Utils::resolvePathCase(m_blfile)).absolutePath() + "/OF.mi4"; if(!QFileInfo(moved).exists()) { - qDebug() << "[BootloaderInstallMi4] renaming" << fwfile << "to" << moved; + LOG_INFO() << "renaming" << fwfile << "to" << moved; oldbl.rename(moved); } else { - qDebug() << "[BootloaderInstallMi4] OF.mi4 already present, not renaming again."; + LOG_INFO() << "OF.mi4 already present, not renaming again."; oldbl.remove(); } // place new bootloader m_tempfile.open(); - qDebug() << "[BootloaderInstallMi4] renaming" << m_tempfile.fileName() - << "to" << fwfile; + LOG_INFO() << "renaming" << m_tempfile.fileName() + << "to" << fwfile; m_tempfile.close(); if(!Utils::resolvePathCase(fwfile).isEmpty()) { emit logItem(tr("A firmware file is already present on player"), LOGERROR); @@ -84,7 +85,7 @@ void BootloaderInstallMi4::installStage2(void) bool BootloaderInstallMi4::uninstall(void) { - qDebug() << "[BootloaderInstallMi4] Uninstalling bootloader"; + LOG_INFO() << "Uninstalling bootloader"; // check if it's actually a Rockbox bootloader emit logItem(tr("Checking for Rockbox bootloader"), LOGINFO); @@ -128,7 +129,7 @@ BootloaderInstallBase::BootloaderType BootloaderInstallMi4::installed(void) QString resolved; resolved = Utils::resolvePathCase(m_blfile); if(resolved.isEmpty()) { - qDebug() << "[BootloaderInstallMi4] installed: BootloaderNone"; + LOG_INFO() << "installed: BootloaderNone"; return BootloaderNone; } @@ -140,11 +141,11 @@ BootloaderInstallBase::BootloaderType BootloaderInstallMi4::installed(void) f.close(); if(!memcmp(magic, "RBBL", 4)) { - qDebug() << "[BootloaderInstallMi4] installed: BootloaderRockbox"; + LOG_INFO() << "installed: BootloaderRockbox"; return BootloaderRockbox; } else { - qDebug() << "[BootloaderInstallMi4] installed: BootloaderOther"; + LOG_INFO() << "installed: BootloaderOther"; return BootloaderOther; } } @@ -152,7 +153,7 @@ BootloaderInstallBase::BootloaderType BootloaderInstallMi4::installed(void) BootloaderInstallBase::Capabilities BootloaderInstallMi4::capabilities(void) { - qDebug() << "[BootloaderInstallMi4] getting capabilities"; + LOG_INFO() << "getting capabilities"; return Install | Uninstall | Backup | IsFile | CanCheckInstalled | CanCheckVersion; } diff --git a/rbutil/rbutilqt/base/bootloaderinstallmpio.cpp b/rbutil/rbutilqt/base/bootloaderinstallmpio.cpp index 52a6f351f1..97b68f7f61 100644 --- a/rbutil/rbutilqt/base/bootloaderinstallmpio.cpp +++ b/rbutil/rbutilqt/base/bootloaderinstallmpio.cpp @@ -20,6 +20,7 @@ #include #include "bootloaderinstallbase.h" #include "bootloaderinstallmpio.h" +#include "Logger.h" #include "../mkmpioboot/mkmpioboot.h" @@ -46,7 +47,7 @@ bool BootloaderInstallMpio::install(void) if(m_offile.isEmpty()) return false; - qDebug() << "[BootloaderInstallMpio] installing bootloader"; + LOG_INFO() << "installing bootloader"; // download firmware from server emit logItem(tr("Downloading bootloader file"), LOGINFO); @@ -59,7 +60,7 @@ bool BootloaderInstallMpio::install(void) void BootloaderInstallMpio::installStage2(void) { - qDebug() << "[BootloaderInstallMpio] installStage2"; + LOG_INFO() << "installStage2"; int origin = 0xe0000; /* MPIO HD200 bootloader address */ @@ -107,14 +108,14 @@ void BootloaderInstallMpio::installStage2(void) break; } - qDebug() << "[BootloaderInstallMpio] Patching original firmware failed:" << error; + LOG_ERROR() << "Patching original firmware failed:" << error; emit logItem(tr("Patching original firmware failed: %1").arg(error), LOGERROR); emit done(true); return; } //end of install - qDebug() << "[BootloaderInstallMpio] install successful"; + LOG_INFO() << "install successful"; emit logItem(tr("Success: modified firmware file created"), LOGINFO); logInstall(LogAdd); emit done(false); diff --git a/rbutil/rbutilqt/base/bootloaderinstallsansa.cpp b/rbutil/rbutilqt/base/bootloaderinstallsansa.cpp index 49099ebaf8..d722dfdf6e 100644 --- a/rbutil/rbutilqt/base/bootloaderinstallsansa.cpp +++ b/rbutil/rbutilqt/base/bootloaderinstallsansa.cpp @@ -19,6 +19,7 @@ #include #include "bootloaderinstallbase.h" #include "bootloaderinstallsansa.h" +#include "Logger.h" #include "../sansapatcher/sansapatcher.h" #include "utils.h" @@ -116,7 +117,7 @@ void BootloaderInstallSansa::installStage2(void) m_tempfile.close(); if(memcmp(sansa.targetname, magic, 4) != 0) { emit logItem(tr("Bootloader mismatch! Aborting."), LOGERROR); - qDebug("[BootloaderInstallSansa] Targetname: %s, mi4 magic: %c%c%c%c", + LOG_INFO("Targetname: %s, mi4 magic: %c%c%c%c", sansa.targetname, magic[0], magic[1], magic[2], magic[3]); emit done(true); sansa_close(&sansa); @@ -157,7 +158,8 @@ void BootloaderInstallSansa::installStage3(bool mounted) emit logItem(tr("Writing log aborted"), LOGERROR); emit done(true); } - qDebug() << "[BootloaderInstallSansa] version installed:" << m_blversion.toString(Qt::ISODate); + LOG_INFO() << "version installed:" + << m_blversion.toString(Qt::ISODate); } @@ -245,8 +247,8 @@ bool BootloaderInstallSansa::sansaInitialize(struct sansa_t *sansa) sprintf(sansa->diskname, qPrintable(devicename.remove(QRegExp("[0-9]+$")))); #endif - qDebug() << "[BootloaderInstallSansa] sansapatcher: overriding scan, using" - << sansa->diskname; + LOG_INFO() << "sansapatcher: overriding scan, using" + << sansa->diskname; } else if(sansa_scan(sansa) != 1) { emit logItem(tr("Can't find Sansa"), LOGERROR); diff --git a/rbutil/rbutilqt/base/encoderexe.cpp b/rbutil/rbutilqt/base/encoderexe.cpp index f0f39daad7..f56cf368eb 100644 --- a/rbutil/rbutilqt/base/encoderexe.cpp +++ b/rbutil/rbutilqt/base/encoderexe.cpp @@ -20,6 +20,7 @@ #include "encoderexe.h" #include "rbsettings.h" #include "utils.h" +#include "Logger.h" EncoderExe::EncoderExe(QString name,QObject *parent) : EncoderBase(parent) { @@ -69,14 +70,13 @@ bool EncoderExe::start() bool EncoderExe::encode(QString input,QString output) { - //qDebug() << "encoding.."; QString execstring = m_EncTemplate; execstring.replace("%exe",m_EncExec); execstring.replace("%options",m_EncOpts); execstring.replace("%input",input); execstring.replace("%output",output); - qDebug() << "[EncoderExe] cmd: " << execstring; + LOG_INFO() << "cmd: " << execstring; int result = QProcess::execute(execstring); return (result == 0) ? true : false; } diff --git a/rbutil/rbutilqt/base/encoderlame.cpp b/rbutil/rbutilqt/base/encoderlame.cpp index c8554194c4..ad283ccf9e 100644 --- a/rbutil/rbutilqt/base/encoderlame.cpp +++ b/rbutil/rbutilqt/base/encoderlame.cpp @@ -20,13 +20,14 @@ #include "encoderlame.h" #include "rbsettings.h" #include "lame/lame.h" +#include "Logger.h" /** Resolve a symbol from loaded library. */ #define SYMBOLRESOLVE(symbol, type) \ do { m_##symbol = (type)lib->resolve(#symbol); \ if(!m_##symbol) return; \ - qDebug() << "[EncoderLame] Resolved symbol " #symbol; } \ + LOG_INFO() << "Resolved symbol " #symbol; } \ while(0) EncoderLame::EncoderLame(QObject *parent) : EncoderBase(parent) @@ -50,7 +51,7 @@ EncoderLame::EncoderLame(QObject *parent) : EncoderBase(parent) SYMBOLRESOLVE(lame_encode_flush, int (*)(lame_global_flags*, unsigned char*, int)); SYMBOLRESOLVE(lame_close, int (*)(lame_global_flags*)); - qDebug() << "[EncoderLame] libmp3lame loaded:" << lib->isLoaded(); + LOG_INFO() << "libmp3lame loaded:" << lib->isLoaded(); m_encoderVolume = RbSettings::subValue("lame", RbSettings::EncoderVolume).toDouble(); m_encoderQuality = RbSettings::subValue("lame", RbSettings::EncoderQuality).toDouble(); @@ -108,9 +109,9 @@ bool EncoderLame::start() bool EncoderLame::encode(QString input,QString output) { - qDebug() << "[EncoderLame] Encoding" << QDir::cleanPath(input); + LOG_INFO() << "Encoding" << QDir::cleanPath(input); if(!m_symbolsResolved) { - qDebug() << "[EncoderLame] Symbols not successfully resolved, cannot run!"; + LOG_ERROR() << "Symbols not successfully resolved, cannot run!"; return false; } @@ -144,21 +145,21 @@ bool EncoderLame::encode(QString input,QString output) m_lame_set_bWriteVbrTag(gfp, 0); // disable LAME tag. if(!fin.open(QIODevice::ReadOnly)) { - qDebug() << "[EncoderLame] Could not open input file" << input; + LOG_ERROR() << "Could not open input file" << input; return false; } // read RIFF header fin.read((char*)header, 12); if(memcmp("RIFF", header, 4) != 0) { - qDebug() << "[EncoderLame] RIFF header not found!" - << header[0] << header[1] << header[2] << header[3]; + LOG_ERROR() << "RIFF header not found!" + << header[0] << header[1] << header[2] << header[3]; fin.close(); return false; } if(memcmp("WAVE", &header[8], 4) != 0) { - qDebug() << "[EncoderLame] WAVE FOURCC not found!" - << header[8] << header[9] << header[10] << header[11]; + LOG_ERROR() << "WAVE FOURCC not found!" + << header[8] << header[9] << header[10] << header[11]; fin.close(); return false; } @@ -178,7 +179,7 @@ bool EncoderLame::encode(QString input,QString output) // input format used should be known. In case some TTS uses a // different wave encoding some time this needs to get adjusted. if(chunkdatalen < 16) { - qDebug() << "[EncoderLame] fmt chunk too small!"; + LOG_ERROR() << "fmt chunk too small!"; } else { unsigned char *buf = new unsigned char[chunkdatalen]; @@ -196,18 +197,18 @@ bool EncoderLame::encode(QString input,QString output) } else { // unknown chunk, just skip its data. - qDebug() << "[EncoderLame] unknown chunk, skipping." - << chunkheader[0] << chunkheader[1] - << chunkheader[2] << chunkheader[3]; + LOG_WARNING() << "unknown chunk, skipping." + << chunkheader[0] << chunkheader[1] + << chunkheader[2] << chunkheader[3]; fin.seek(fin.pos() + chunkdatalen); } } while(!fin.atEnd()); // check format if(channels == 0 || samplerate == 0 || samplesize == 0 || datalength == 0) { - qDebug() << "[EncoderLame] invalid format. Channels:" << channels - << "Samplerate:" << samplerate << "Samplesize:" << samplesize - << "Data chunk length:" << datalength; + LOG_ERROR() << "invalid format. Channels:" << channels + << "Samplerate:" << samplerate << "Samplesize:" << samplesize + << "Data chunk length:" << datalength; fin.close(); return false; } @@ -220,7 +221,7 @@ bool EncoderLame::encode(QString input,QString output) // initialize encoder. ret = m_lame_init_params(gfp); if(ret != 0) { - qDebug() << "[EncoderLame] lame_init_params() failed with" << ret; + LOG_ERROR() << "lame_init_params() failed with" << ret; fin.close(); return false; } @@ -230,7 +231,7 @@ bool EncoderLame::encode(QString input,QString output) // bytes the input file has. This wastes space but should be ok. // Put an upper limit of 8MiB. if(datalength > 8*1024*1024) { - qDebug() << "[EncoderLame] Input file too large:" << datalength; + LOG_ERROR() << "Input file too large:" << datalength; fin.close(); return false; } @@ -255,7 +256,7 @@ bool EncoderLame::encode(QString input,QString output) } } else { - qDebug() << "[EncoderLame] Unknown samplesize:" << samplesize; + LOG_ERROR() << "Unknown samplesize:" << samplesize; fin.close(); delete[] mp3buf; delete[] wavbuf; @@ -270,10 +271,10 @@ bool EncoderLame::encode(QString input,QString output) fout.open(QIODevice::ReadWrite); ret = m_lame_encode_buffer(gfp, wavbuf, wavbuf, num_samples, mp3buf, mp3buflen); if(ret < 0) { - qDebug() << "[EncoderLame] Error during encoding:" << ret; + LOG_ERROR() << "Error during encoding:" << ret; } if(fout.write((char*)mp3buf, ret) != (unsigned int)ret) { - qDebug() << "[EncoderLame] Writing mp3 data failed!" << ret; + LOG_ERROR() << "Writing mp3 data failed!" << ret; fout.close(); delete[] mp3buf; delete[] wavbuf; @@ -282,7 +283,7 @@ bool EncoderLame::encode(QString input,QString output) // flush remaining data ret = m_lame_encode_flush(gfp, mp3buf, mp3buflen); if(fout.write((char*)mp3buf, ret) != (unsigned int)ret) { - qDebug() << "[EncoderLame] Writing final mp3 data failed!"; + LOG_ERROR() << "Writing final mp3 data failed!"; fout.close(); delete[] mp3buf; delete[] wavbuf; diff --git a/rbutil/rbutilqt/base/encoderrbspeex.cpp b/rbutil/rbutilqt/base/encoderrbspeex.cpp index a8b7555fa9..0fc0293685 100644 --- a/rbutil/rbutilqt/base/encoderrbspeex.cpp +++ b/rbutil/rbutilqt/base/encoderrbspeex.cpp @@ -20,6 +20,7 @@ #include "encoderrbspeex.h" #include "rbsettings.h" #include "rbspeex.h" +#include "Logger.h" EncoderRbSpeex::EncoderRbSpeex(QObject *parent) : EncoderBase(parent) { @@ -78,16 +79,16 @@ bool EncoderRbSpeex::start() bool EncoderRbSpeex::encode(QString input,QString output) { - qDebug() << "[RbSpeex] Encoding " << input << " to "<< output; + LOG_INFO() << "Encoding " << input << " to "<< output; char errstr[512]; FILE *fin,*fout; if ((fin = fopen(input.toLocal8Bit(), "rb")) == NULL) { - qDebug() << "[RbSpeex] Error: could not open input file\n"; + LOG_ERROR() << "Error: could not open input file\n"; return false; } if ((fout = fopen(output.toLocal8Bit(), "wb")) == NULL) { - qDebug() << "[RbSpeex] Error: could not open output file\n"; + LOG_ERROR() << "Error: could not open output file\n"; fclose(fin); return false; } @@ -99,7 +100,7 @@ bool EncoderRbSpeex::encode(QString input,QString output) if (!ret) { /* Attempt to delete unfinished output */ - qDebug() << "[RbSpeex] Error:" << errstr; + LOG_ERROR() << "Error:" << errstr; QFile(output).remove(); return false; } diff --git a/rbutil/rbutilqt/base/httpget.cpp b/rbutil/rbutilqt/base/httpget.cpp index e6b9eb4d3c..4b08faf33b 100644 --- a/rbutil/rbutilqt/base/httpget.cpp +++ b/rbutil/rbutilqt/base/httpget.cpp @@ -23,6 +23,7 @@ #include #include "httpget.h" +#include "Logger.h" QString HttpGet::m_globalUserAgent; //< globally set user agent for requests QDir HttpGet::m_globalCache; //< global cach path value for new objects @@ -71,14 +72,14 @@ void HttpGet::setCache(bool c) QString path = m_cachedir.absolutePath(); if(!c || m_cachedir.absolutePath().isEmpty()) { - qDebug() << "[HttpGet] disabling download cache"; + LOG_INFO() << "disabling download cache"; } else { // append the cache path to make it unique in case the path points to // the system temporary path. In that case using it directly might // cause problems. Extra path also used in configure dialog. path += "/rbutil-cache"; - qDebug() << "[HttpGet] setting cache folder to" << path; + LOG_INFO() << "setting cache folder to" << path; m_cache = new QNetworkDiskCache(this); m_cache->setCacheDirectory(path); } @@ -97,7 +98,7 @@ QByteArray HttpGet::readAll() void HttpGet::setProxy(const QUrl &proxy) { - qDebug() << "[HttpGet] Proxy set to" << proxy; + LOG_INFO() << "Proxy set to" << proxy; m_proxy.setType(QNetworkProxy::HttpProxy); m_proxy.setHostName(proxy.host()); m_proxy.setPort(proxy.port()); @@ -130,10 +131,10 @@ void HttpGet::requestFinished(QNetworkReply* reply) { m_lastStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - qDebug() << "[HttpGet] Request finished, status code:" << m_lastStatusCode; + LOG_INFO() << "Request finished, status code:" << m_lastStatusCode; m_lastServerTimestamp = reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toLocalTime(); - qDebug() << "[HttpGet] Data from cache:" + LOG_INFO() << "Data from cache:" << reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); m_lastRequestCached = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); @@ -150,7 +151,7 @@ void HttpGet::requestFinished(QNetworkReply* reply) #else url.setQuery(org.query()); #endif - qDebug() << "[HttpGet] Redirected to" << url; + LOG_INFO() << "Redirected to" << url; startRequest(url); return; } @@ -179,7 +180,7 @@ void HttpGet::downloadProgress(qint64 received, qint64 total) void HttpGet::startRequest(QUrl url) { - qDebug() << "[HttpGet] Request started"; + LOG_INFO() << "Request started"; QNetworkRequest req(url); if(!m_globalUserAgent.isEmpty()) req.setRawHeader("User-Agent", m_globalUserAgent.toLatin1()); @@ -194,15 +195,14 @@ void HttpGet::startRequest(QUrl url) void HttpGet::networkError(QNetworkReply::NetworkError error) { - qDebug() << "[HttpGet] NetworkError occured:" - << error << m_reply->errorString(); + LOG_ERROR() << "NetworkError occured:" << error << m_reply->errorString(); m_lastErrorString = m_reply->errorString(); } bool HttpGet::getFile(const QUrl &url) { - qDebug() << "[HttpGet] Get URI" << url.toString(); + LOG_INFO() << "Get URI" << url.toString(); m_data.clear(); startRequest(url); diff --git a/rbutil/rbutilqt/base/httpget.h b/rbutil/rbutilqt/base/httpget.h index 2f6448a40d..8c62157e5f 100644 --- a/rbutil/rbutilqt/base/httpget.h +++ b/rbutil/rbutilqt/base/httpget.h @@ -25,6 +25,7 @@ #include #include #include +#include "Logger.h" class HttpGet : public QObject { @@ -49,13 +50,13 @@ class HttpGet : public QObject //< set global cache path static void setGlobalCache(const QDir& d) { - qDebug() << "[HttpGet] Global cache set to" << d.absolutePath(); + LOG_INFO() << "Global cache set to" << d.absolutePath(); m_globalCache = d; } //< set global proxy value static void setGlobalProxy(const QUrl& p) { - qDebug() << "[HttpGet] setting global proxy" << p; + LOG_INFO() << "setting global proxy" << p; if(!p.isValid() || p.isEmpty()) { HttpGet::m_globalProxy.setType(QNetworkProxy::NoProxy); } diff --git a/rbutil/rbutilqt/base/mspackutil.cpp b/rbutil/rbutilqt/base/mspackutil.cpp index 4bc7307cd9..1ee250cd6d 100644 --- a/rbutil/rbutilqt/base/mspackutil.cpp +++ b/rbutil/rbutilqt/base/mspackutil.cpp @@ -17,7 +17,7 @@ ****************************************************************************/ #include -#include +#include "Logger.h" #include "mspackutil.h" #include "progressloggerinterface.h" @@ -27,7 +27,7 @@ MsPackUtil::MsPackUtil(QObject* parent) m_cabd = mspack_create_cab_decompressor(NULL); m_cabinet = NULL; if(!m_cabd) - qDebug() << "[MsPackUtil] CAB decompressor creation failed!"; + LOG_ERROR() << "CAB decompressor creation failed!"; } MsPackUtil::~MsPackUtil() @@ -43,7 +43,7 @@ bool MsPackUtil::open(QString& mspackfile) if(m_cabd == NULL) { - qDebug() << "[MsPackUtil] No CAB decompressor available: cannot open file!"; + LOG_ERROR() << "No CAB decompressor available: cannot open file!"; return false; } m_cabinet = m_cabd->search(m_cabd, QFile::encodeName(mspackfile).constData()); @@ -60,10 +60,10 @@ bool MsPackUtil::close(void) bool MsPackUtil::extractArchive(const QString& dest, QString file) { - qDebug() << "[MsPackUtil] extractArchive" << dest << file; + LOG_INFO() << "extractArchive" << dest << file; if(!m_cabinet) { - qDebug() << "[MsPackUtil] CAB file not open!"; + LOG_ERROR() << "CAB file not open!"; return false; } @@ -78,7 +78,7 @@ bool MsPackUtil::extractArchive(const QString& dest, QString file) struct mscabd_file *f = m_cabinet->files; if(f == NULL) { - qDebug() << "[MsPackUtil] CAB doesn't contain file" << file; + LOG_WARNING() << "CAB doesn't contain file" << file; return true; } bool found = false; @@ -99,7 +99,7 @@ bool MsPackUtil::extractArchive(const QString& dest, QString file) if(!QDir().mkpath(QFileInfo(path).absolutePath())) { emit logItem(tr("Creating output path failed"), LOGERROR); - qDebug() << "[MsPackUtil] creating output path failed for:" << path; + LOG_ERROR() << "creating output path failed for:" << path; emit logProgress(1, 1); return false; } @@ -107,7 +107,8 @@ bool MsPackUtil::extractArchive(const QString& dest, QString file) if(ret != MSPACK_ERR_OK) { emit logItem(tr("Error during CAB operation"), LOGERROR); - qDebug() << "[MsPackUtil] mspack error: " << ret << "(" << errorStringMsPack(ret) << ")"; + LOG_ERROR() << "mspack error: " << ret + << "(" << errorStringMsPack(ret) << ")"; emit logProgress(1, 1); return false; } @@ -125,7 +126,7 @@ QStringList MsPackUtil::files(void) QStringList list; if(!m_cabinet) { - qDebug() << "[MsPackUtil] CAB file not open!"; + LOG_WARNING() << "CAB file not open!"; return list; } struct mscabd_file *file = m_cabinet->files; diff --git a/rbutil/rbutilqt/base/rbsettings.cpp b/rbutil/rbutilqt/base/rbsettings.cpp index a2f801844b..854883c4dd 100644 --- a/rbutil/rbutilqt/base/rbsettings.cpp +++ b/rbutil/rbutilqt/base/rbsettings.cpp @@ -19,6 +19,7 @@ #include "rbsettings.h" #include "systeminfo.h" #include +#include "Logger.h" #if defined(Q_OS_LINUX) #include @@ -96,13 +97,13 @@ void RbSettings::ensureRbSettingsExists() { userSettings = new QSettings(QCoreApplication::instance()->applicationDirPath() + "/RockboxUtility.ini", QSettings::IniFormat, NULL); - qDebug() << "[Settings] configuration: portable"; + LOG_INFO() << "configuration: portable"; } else { userSettings = new QSettings(QSettings::IniFormat, QSettings::UserScope, "rockbox.org", "RockboxUtility",NULL); - qDebug() << "[Settings] configuration: system"; + LOG_INFO() << "configuration: system"; } } } @@ -158,7 +159,7 @@ QVariant RbSettings::subValue(QString sub, enum UserSettings setting) i++; QString s = constructSettingPath(UserSettingsList[i].name, sub); - qDebug() << "[Settings] GET U:" << s << userSettings->value(s).toString(); + LOG_INFO() << "GET U:" << s << userSettings->value(s).toString(); return userSettings->value(s, UserSettingsList[i].def); } @@ -179,7 +180,7 @@ void RbSettings::setSubValue(QString sub, enum UserSettings setting, QVariant va QString s = constructSettingPath(UserSettingsList[i].name, sub); userSettings->setValue(s, value); - qDebug() << "[Settings] SET U:" << s << userSettings->value(s).toString(); + LOG_INFO() << "SET U:" << s << userSettings->value(s).toString(); } QString RbSettings::constructSettingPath(QString path, QString substitute) diff --git a/rbutil/rbutilqt/base/rockboxinfo.cpp b/rbutil/rbutilqt/base/rockboxinfo.cpp index e5bce09d2c..f34adbfc2f 100644 --- a/rbutil/rbutilqt/base/rockboxinfo.cpp +++ b/rbutil/rbutilqt/base/rockboxinfo.cpp @@ -20,10 +20,11 @@ #include #include +#include "Logger.h" RockboxInfo::RockboxInfo(QString mountpoint, QString fname) { - qDebug() << "[RockboxInfo] Getting version info from rockbox-info.txt"; + LOG_INFO() << "Getting version info from rockbox-info.txt"; QFile file(mountpoint + "/" + fname); m_success = false; m_voicefmt = 400; // default value for compatibility diff --git a/rbutil/rbutilqt/base/serverinfo.cpp b/rbutil/rbutilqt/base/serverinfo.cpp index 8d91309e66..4773c1ee71 100644 --- a/rbutil/rbutilqt/base/serverinfo.cpp +++ b/rbutil/rbutilqt/base/serverinfo.cpp @@ -19,6 +19,7 @@ #include "serverinfo.h" #include "rbsettings.h" #include "systeminfo.h" +#include "Logger.h" #if defined(Q_OS_LINUX) #include @@ -181,7 +182,7 @@ QVariant ServerInfo::value(enum ServerInfos info) QString s = ServerInfoList[i].name; s.replace(":platform:", RbSettings::value(RbSettings::CurrentPlatform).toString()); - qDebug() << "[ServerInfo] GET:" << s << serverInfos.value(s, ServerInfoList[i].def).toString(); + LOG_INFO() << "GET:" << s << serverInfos.value(s, ServerInfoList[i].def).toString(); return serverInfos.value(s, ServerInfoList[i].def); } @@ -201,7 +202,7 @@ void ServerInfo::setPlatformValue(QString platform, enum ServerInfos info, QVari QString s = ServerInfoList[i].name; s.replace(":platform:", platform); serverInfos.insert(s, value); - qDebug() << "[ServerInfo] SET:" << s << serverInfos.value(s).toString(); + LOG_INFO() << "SET:" << s << serverInfos.value(s).toString(); } QVariant ServerInfo::platformValue(QString platform, enum ServerInfos info) @@ -215,7 +216,7 @@ QVariant ServerInfo::platformValue(QString platform, enum ServerInfos info) s.replace(":platform:", platform); QString d = ServerInfoList[i].def; d.replace(":platform:", platform); - qDebug() << "[ServerInfo] GET:" << s << serverInfos.value(s, d).toString(); + LOG_INFO() << "GET:" << s << serverInfos.value(s, d).toString(); return serverInfos.value(s, d); } diff --git a/rbutil/rbutilqt/base/system.cpp b/rbutil/rbutilqt/base/system.cpp index fd3b04e338..117e5dc9b4 100644 --- a/rbutil/rbutilqt/base/system.cpp +++ b/rbutil/rbutilqt/base/system.cpp @@ -69,6 +69,7 @@ #include "utils.h" #include "rbsettings.h" +#include "Logger.h" /** @brief detect permission of user (only Windows at moment). * @return enum userlevel. @@ -242,17 +243,17 @@ QMap System::listUsbDevices(void) { QMap usbids; // usb pid detection - qDebug() << "[System] Searching for USB devices"; + LOG_INFO() << "Searching for USB devices"; #if defined(Q_OS_LINUX) #if defined(LIBUSB1) libusb_device **devs; if(libusb_init(NULL) != 0) { - qDebug() << "[System] Initializing libusb-1 failed."; + LOG_ERROR() << "Initializing libusb-1 failed."; return usbids; } if(libusb_get_device_list(NULL, &devs) < 1) { - qDebug() << "[System] Error getting device list."; + LOG_ERROR() << "Error getting device list."; return usbids; } libusb_device *dev; @@ -277,7 +278,7 @@ QMap System::listUsbDevices(void) name = tr("(no description available)"); if(id) { usbids.insertMulti(id, name); - qDebug("[System] USB: 0x%08x, %s", id, name.toLocal8Bit().data()); + LOG_INFO("USB: 0x%08x, %s", id, name.toLocal8Bit().data()); } } } @@ -323,7 +324,7 @@ QMap System::listUsbDevices(void) if(id) { usbids.insertMulti(id, name); - qDebug() << "[System] USB:" << QString("0x%1").arg(id, 8, 16) << name; + LOG_INFO() << "USB:" << QString("0x%1").arg(id, 8, 16) << name; } u = u->next; } @@ -341,7 +342,7 @@ QMap System::listUsbDevices(void) result = IOServiceGetMatchingServices(kIOMasterPortDefault, usb_matching_dictionary, &usb_iterator); if(result) { - qDebug() << "[System] USB: IOKit: Could not get matching services."; + LOG_ERROR() << "USB: IOKit: Could not get matching services."; return usbids; } @@ -404,7 +405,7 @@ QMap System::listUsbDevices(void) if(id) { usbids.insertMulti(id, name); - qDebug() << "[System] USB:" << QString("0x%1").arg(id, 8, 16) << name; + LOG_INFO() << "USB:" << QString("0x%1").arg(id, 8, 16) << name; } } @@ -468,7 +469,7 @@ QMap System::listUsbDevices(void) uint32_t id; id = vid << 16 | pid; usbids.insert(id, description); - qDebug("[System] USB VID: %04x, PID: %04x", vid, pid); + LOG_INFO("USB VID: %04x, PID: %04x", vid, pid); } if(buffer) free(buffer); } @@ -507,7 +508,7 @@ QUrl System::systemProxy(void) RegCloseKey(hk); - //qDebug() << QString::fromWCharArray(proxyval) << QString("%1").arg(enable); + //LOG_INFO() << QString::fromWCharArray(proxyval) << QString("%1").arg(enable); if(enable != 0) return QUrl("http://" + QString::fromWCharArray(proxyval)); else @@ -537,7 +538,7 @@ QUrl System::systemProxy(void) bufsize = CFStringGetLength(stringref) * 2 + 1; buf = (char*)malloc(sizeof(char) * bufsize); if(buf == NULL) { - qDebug() << "[System] can't allocate memory for proxy string!"; + LOG_ERROR() << "can't allocate memory for proxy string!"; CFRelease(dictref); return QUrl(""); } diff --git a/rbutil/rbutilqt/base/systeminfo.cpp b/rbutil/rbutilqt/base/systeminfo.cpp index 971a1196ac..d75b90c22d 100644 --- a/rbutil/rbutilqt/base/systeminfo.cpp +++ b/rbutil/rbutilqt/base/systeminfo.cpp @@ -16,10 +16,11 @@ * ****************************************************************************/ -#include "systeminfo.h" +#include "systeminfo.h" #include "rbsettings.h" #include +#include "Logger.h" #if defined(Q_OS_LINUX) #include @@ -89,7 +90,7 @@ QVariant SystemInfo::value(enum SystemInfos info) s.replace(":platform:", platform); QString d = SystemInfosList[i].def; d.replace(":platform:", platform); - qDebug() << "[SystemInfo] GET:" << s << systemInfos->value(s, d).toString(); + LOG_INFO() << "GET:" << s << systemInfos->value(s, d).toString(); return systemInfos->value(s, d); } @@ -106,7 +107,7 @@ QVariant SystemInfo::platformValue(QString platform, enum SystemInfos info) s.replace(":platform:", platform); QString d = SystemInfosList[i].def; d.replace(":platform:", platform); - qDebug() << "[SystemInfo] GET P:" << s << systemInfos->value(s, d).toString(); + LOG_INFO() << "GET P:" << s << systemInfos->value(s, d).toString(); return systemInfos->value(s, d); } diff --git a/rbutil/rbutilqt/base/talkfile.cpp b/rbutil/rbutilqt/base/talkfile.cpp index dc4dceef08..1e9a968576 100644 --- a/rbutil/rbutilqt/base/talkfile.cpp +++ b/rbutil/rbutilqt/base/talkfile.cpp @@ -18,6 +18,7 @@ #include "talkfile.h" #include "rbsettings.h" +#include "Logger.h" TalkFileCreator::TalkFileCreator(QObject* parent): QObject(parent) { @@ -109,7 +110,7 @@ void TalkFileCreator::doAbort() //! \param startDir The directory from which to start scanning bool TalkFileCreator::createTalkList(QDir startDir) { - qDebug() << "[TalkGenerator] generating list of files" << startDir; + LOG_INFO() << "generating list of files" << startDir; m_talkList.clear(); // create Iterator @@ -161,9 +162,9 @@ bool TalkFileCreator::createTalkList(QDir startDir) entry.target = dir.path() + "/_dirname.talk"; entry.voiced = false; entry.encoded = false; - qDebug() << "[TalkFileCreator] toSpeak:" << entry.toSpeak - << "target:" << entry.target - << "intermediates:" << entry.wavfilename << entry.talkfilename; + LOG_INFO() << "toSpeak:" << entry.toSpeak + << "target:" << entry.target + << "intermediates:" << entry.wavfilename << entry.talkfilename; m_talkList.append(entry); } } @@ -205,16 +206,16 @@ bool TalkFileCreator::createTalkList(QDir startDir) entry.target = fileInf.path() + "/" + fileInf.fileName() + ".talk"; entry.voiced = false; entry.encoded = false; - qDebug() << "[TalkFileCreator] toSpeak:" << entry.toSpeak - << "target:" << entry.target - << "intermediates:" << - entry.wavfilename << entry.talkfilename; + LOG_INFO() << "toSpeak:" << entry.toSpeak + << "target:" << entry.target + << "intermediates:" + << entry.wavfilename << entry.talkfilename; m_talkList.append(entry); } } QCoreApplication::processEvents(); } - qDebug() << "[TalkFileCreator] list created, entries:" << m_talkList.size(); + LOG_INFO() << "list created, entries:" << m_talkList.size(); return true; } @@ -251,8 +252,8 @@ bool TalkFileCreator::copyTalkFiles(QString* errString) QFile::remove(m_talkList[i].target); // copying - qDebug() << "[TalkFileCreator] copying" << m_talkList[i].talkfilename - << "to" << m_talkList[i].target; + LOG_INFO() << "copying" << m_talkList[i].talkfilename + << "to" << m_talkList[i].target; if(!QFile::copy(m_talkList[i].talkfilename,m_talkList[i].target)) { *errString = tr("Copying of %1 to %2 failed").arg(m_talkList[i].talkfilename).arg(m_talkList[i].target); diff --git a/rbutil/rbutilqt/base/talkgenerator.cpp b/rbutil/rbutilqt/base/talkgenerator.cpp index a2ab578ade..32686c78c2 100644 --- a/rbutil/rbutilqt/base/talkgenerator.cpp +++ b/rbutil/rbutilqt/base/talkgenerator.cpp @@ -20,6 +20,7 @@ #include "rbsettings.h" #include "systeminfo.h" #include "wavtrim.h" +#include "Logger.h" TalkGenerator::TalkGenerator(QObject* parent): QObject(parent) { @@ -39,7 +40,7 @@ TalkGenerator::Status TalkGenerator::process(QList* list,int wavtrimt m_tts = TTSBase::getTTS(this, RbSettings::value(RbSettings::Tts).toString()); if(!m_tts) { - qDebug() << "[TalkGenerator] getting the TTS object failed!"; + LOG_ERROR() << "getting the TTS object failed!"; emit logItem(tr("Init of TTS engine failed"), LOGERROR); emit done(true); return eERROR; @@ -131,7 +132,7 @@ TalkGenerator::Status TalkGenerator::voiceList(QList* list,int wavtri duplicates.append(list->at(i).wavfilename); else { - qDebug() << "[TalkGenerator] duplicate skipped"; + LOG_INFO() << "duplicate skipped"; (*list)[i].voiced = true; emit logProgress(++m_progress,progressMax); continue; @@ -152,7 +153,7 @@ TalkGenerator::Status TalkGenerator::voiceList(QList* list,int wavtri // voice entry QString error; - qDebug() << "[TalkGenerator] voicing: " << list->at(i).toSpeak + LOG_INFO() << "voicing: " << list->at(i).toSpeak << "to" << list->at(i).wavfilename; TTSStatus status = m_tts->voice(list->at(i).toSpeak,list->at(i).wavfilename, &error); if(status == Warning) @@ -177,8 +178,8 @@ TalkGenerator::Status TalkGenerator::voiceList(QList* list,int wavtri if(wavtrim(list->at(i).wavfilename.toLocal8Bit().data(), wavtrimth, buffer, 255)) { - qDebug() << "[TalkGenerator] wavtrim returned error on" - << list->at(i).wavfilename; + LOG_ERROR() << "wavtrim returned error on" + << list->at(i).wavfilename; return eERROR; } } @@ -214,8 +215,8 @@ TalkGenerator::Status TalkGenerator::encodeList(QList* list) //skip non-voiced entrys if(list->at(i).voiced == false) { - qDebug() << "[TalkGenerator] non voiced entry detected:" - << list->at(i).toSpeak; + LOG_WARNING() << "non voiced entry detected:" + << list->at(i).toSpeak; emit logProgress(++m_progress,progressMax); continue; } @@ -224,15 +225,15 @@ TalkGenerator::Status TalkGenerator::encodeList(QList* list) duplicates.append(list->at(i).talkfilename); else { - qDebug() << "[TalkGenerator] duplicate skipped"; + LOG_INFO() << "duplicate skipped"; (*list)[i].encoded = true; emit logProgress(++m_progress,progressMax); continue; } //encode entry - qDebug() << "[TalkGenerator] encoding " << list->at(i).wavfilename - << "to" << list->at(i).talkfilename; + LOG_INFO() << "encoding " << list->at(i).wavfilename + << "to" << list->at(i).talkfilename; if(!m_enc->encode(list->at(i).wavfilename,list->at(i).talkfilename)) { emit logItem(tr("Encoding of %1 failed").arg( @@ -268,7 +269,7 @@ QString TalkGenerator::correctString(QString s) } if(corrected != s) - qDebug() << "[VoiceFileCreator] corrected string" << s << "to" << corrected; + LOG_INFO() << "corrected string" << s << "to" << corrected; return corrected; m_abort = true; @@ -287,7 +288,7 @@ void TalkGenerator::setLang(QString name) TTSBase* tts = TTSBase::getTTS(this,RbSettings::value(RbSettings::Tts).toString()); if(!tts) { - qDebug() << "[TalkGenerator] getting the TTS object failed!"; + LOG_ERROR() << "getting the TTS object failed!"; return; } QString vendor = tts->voiceVendor(); @@ -295,8 +296,8 @@ void TalkGenerator::setLang(QString name) if(m_lang.isEmpty()) m_lang = "english"; - qDebug() << "[TalkGenerator] building string corrections list for" - << m_lang << engine << vendor; + LOG_INFO() << "building string corrections list for" + << m_lang << engine << vendor; QTextStream stream(&correctionsFile); while(!stream.atEnd()) { QString line = stream.readLine(); diff --git a/rbutil/rbutilqt/base/ttscarbon.cpp b/rbutil/rbutilqt/base/ttscarbon.cpp index ff7709dc63..a01d402cd4 100644 --- a/rbutil/rbutilqt/base/ttscarbon.cpp +++ b/rbutil/rbutilqt/base/ttscarbon.cpp @@ -28,6 +28,7 @@ #include #include #include +#include "Logger.h" TTSCarbon::TTSCarbon(QObject* parent) : TTSBase(parent) { @@ -74,7 +75,7 @@ bool TTSCarbon::start(QString *errStr) if(voiceIndex == numVoices) { // voice not found. Add user notification here and proceed with // system default voice. - qDebug() << "[TTSCarbon] Selected voice not found, using system default!"; + LOG_WARNING() << "Selected voice not found, using system default!"; GetVoiceDescription(&vspec, &vdesc, sizeof(vdesc)); if(vdesc.script != -1) m_voiceScript = (CFStringBuiltInEncodings)vdesc.script; diff --git a/rbutil/rbutilqt/base/ttsexes.cpp b/rbutil/rbutilqt/base/ttsexes.cpp index 348db103bc..a8c10bfb19 100644 --- a/rbutil/rbutilqt/base/ttsexes.cpp +++ b/rbutil/rbutilqt/base/ttsexes.cpp @@ -20,6 +20,7 @@ #include "ttsexes.h" #include "utils.h" #include "rbsettings.h" +#include "Logger.h" TTSExes::TTSExes(QObject* parent) : TTSBase(parent) { @@ -85,15 +86,15 @@ TTSStatus TTSExes::voice(QString text, QString wavfile, QString *errStr) QString execstring; if(wavfile.isEmpty() && m_capabilities & TTSBase::CanSpeak) { if(m_TTSSpeakTemplate.isEmpty()) { - qDebug() << "[TTSExes] internal error: TTS announces CanSpeak " - "but template empty!"; + LOG_ERROR() << "internal error: TTS announces CanSpeak " + "but template empty!"; return FatalError; } execstring = m_TTSSpeakTemplate; } else if(wavfile.isEmpty()) { - qDebug() << "[TTSExes] no output file passed to voice() " - "but TTS can't speak directly."; + LOG_ERROR() << "no output file passed to voice() " + "but TTS can't speak directly."; return FatalError; } else { @@ -108,7 +109,7 @@ TTSStatus TTSExes::voice(QString text, QString wavfile, QString *errStr) QProcess::execute(execstring); if(!wavfile.isEmpty() && !QFileInfo(wavfile).isFile()) { - qDebug() << "[TTSExes] output file does not exist:" << wavfile; + LOG_ERROR() << "output file does not exist:" << wavfile; return FatalError; } return NoError; diff --git a/rbutil/rbutilqt/base/ttsfestival.cpp b/rbutil/rbutilqt/base/ttsfestival.cpp index cbf24a3f03..41358ba488 100644 --- a/rbutil/rbutilqt/base/ttsfestival.cpp +++ b/rbutil/rbutilqt/base/ttsfestival.cpp @@ -22,10 +22,11 @@ #include "ttsfestival.h" #include "utils.h" #include "rbsettings.h" +#include "Logger.h" TTSFestival::~TTSFestival() { - qDebug() << "[Festival] Destroying instance"; + LOG_INFO() << "Destroying instance"; stop(); } @@ -87,7 +88,7 @@ void TTSFestival::updateVoiceDescription() currentPath = getSetting(eSERVERPATH)->current().toString(); QString info = getVoiceInfo(getSetting(eVOICE)->current().toString()); currentPath = ""; - + getSetting(eVOICEDESC)->setCurrent(info); } @@ -101,7 +102,7 @@ void TTSFestival::updateVoiceList() currentPath = getSetting(eSERVERPATH)->current().toString(); QStringList voiceList = getVoiceList(); currentPath = ""; - + getSetting(eVOICE)->setList(voiceList); if(voiceList.size() > 0) getSetting(eVOICE)->setCurrent(voiceList.at(0)); else getSetting(eVOICE)->setCurrent(""); @@ -130,9 +131,10 @@ void TTSFestival::startServer() QCoreApplication::processEvents(QEventLoop::AllEvents, 50); if(serverProcess.state() == QProcess::Running) - qDebug() << "[Festival] Server is up and running"; + LOG_INFO() << "Server is up and running"; else - qDebug() << "[Festival] Server failed to start, state: " << serverProcess.state(); + LOG_ERROR() << "Server failed to start, state:" + << serverProcess.state(); } } @@ -147,8 +149,9 @@ bool TTSFestival::ensureServerRunning() bool TTSFestival::start(QString* errStr) { - qDebug() << "[Festival] Starting server with voice " << RbSettings::subValue("festival", RbSettings::TtsVoice).toString(); - + LOG_INFO() << "Starting server with voice" + << RbSettings::subValue("festival", RbSettings::TtsVoice).toString(); + bool running = ensureServerRunning(); if (!RbSettings::subValue("festival",RbSettings::TtsVoice).toString().isEmpty()) { @@ -156,17 +159,17 @@ bool TTSFestival::start(QString* errStr) QString voiceSelect = QString("(voice.select '%1)\n") .arg(RbSettings::subValue("festival", RbSettings::TtsVoice).toString()); queryServer(voiceSelect, 3000); - + if(prologFile.open()) { prologFile.write(voiceSelect.toLatin1()); prologFile.close(); prologPath = QFileInfo(prologFile).absoluteFilePath(); - qDebug() << "[Festival] Prolog created at " << prologPath; + LOG_INFO() << "Prolog created at" << prologPath; } - + } - + if (!running) (*errStr) = "Festival could not be started"; return running; @@ -182,13 +185,13 @@ bool TTSFestival::stop() TTSStatus TTSFestival::voice(QString text, QString wavfile, QString* errStr) { - qDebug() << "[Festival] Voicing " << text << "->" << wavfile; + LOG_INFO() << "Voicing" << text << "->" << wavfile; QString path = RbSettings::subValue("festival-client", RbSettings::TtsPath).toString(); QString cmd = QString("%1 --server localhost --otype riff --ttw --withlisp" " --output \"%2\" --prolog \"%3\" - ").arg(path).arg(wavfile).arg(prologPath); - qDebug() << "[Festival] Client cmd: " << cmd; + LOG_INFO() << "Client cmd:" << cmd; QProcess clientProcess; clientProcess.start(cmd); @@ -200,7 +203,7 @@ TTSStatus TTSFestival::voice(QString text, QString wavfile, QString* errStr) response = response.trimmed(); if(!response.contains("Utterance")) { - qDebug() << "[Festival] Could not voice string: " << response; + LOG_WARNING() << "Could not voice string: " << response; *errStr = tr("engine could not voice string"); return Warning; /* do not stop the voicing process because of a single string @@ -231,10 +234,10 @@ bool TTSFestival::configOk() ret = ret && (voices.indexOf(RbSettings::subValue("festival", RbSettings::TtsVoice).toString()) != -1); } - else /* If we're currently configuring the server, we need to know that + else /* If we're currently configuring the server, we need to know that the entered path is valid */ ret = QFileInfo(currentPath).isExecutable(); - + return ret; } @@ -245,7 +248,7 @@ QStringList TTSFestival::getVoiceList() if(voices.size() > 0) { - qDebug() << "[Festival] Using voice cache"; + LOG_INFO() << "Using voice cache"; return voices; } @@ -261,9 +264,9 @@ QStringList TTSFestival::getVoiceList() if (voices.size() == 1 && voices[0].size() == 0) voices.removeAt(0); if (voices.size() > 0) - qDebug() << "[Festival] Voices: " << voices; + LOG_INFO() << "Voices:" << voices; else - qDebug() << "[Festival] No voices. Response was: " << response; + LOG_WARNING() << "No voices. Response was:" << response; return voices; } @@ -290,7 +293,7 @@ QString TTSFestival::getVoiceInfo(QString voice) { response = response.remove(QRegExp("(description \"*\")", Qt::CaseInsensitive, QRegExp::Wildcard)); - qDebug() << "[Festival] voiceInfo w/o descr: " << response; + LOG_INFO() << "voiceInfo w/o descr:" << response; response = response.remove(')'); QStringList responseLines = response.split('(', QString::SkipEmptyParts); responseLines.removeAt(0); // the voice name itself @@ -327,12 +330,12 @@ QString TTSFestival::queryServer(QString query, int timeout) // this operation could take some time emit busy(); - - qDebug() << "[Festival] queryServer with " << query; + + LOG_INFO() << "queryServer with" << query; if (!ensureServerRunning()) { - qDebug() << "[Festival] queryServer: ensureServerRunning failed"; + LOG_ERROR() << "queryServer: ensureServerRunning failed"; emit busyEnd(); return ""; } @@ -393,7 +396,7 @@ QString TTSFestival::queryServer(QString query, int timeout) lines.removeLast(); /* should be ft_StUfF_keyOK */ } else - qDebug() << "[Festival] Response too short: " << response; + LOG_ERROR() << "Response too short:" << response; emit busyEnd(); return lines.join("\n"); diff --git a/rbutil/rbutilqt/base/ttssapi.cpp b/rbutil/rbutilqt/base/ttssapi.cpp index 603e7c5559..320ee1191a 100644 --- a/rbutil/rbutilqt/base/ttssapi.cpp +++ b/rbutil/rbutilqt/base/ttssapi.cpp @@ -20,6 +20,7 @@ #include "utils.h" #include "rbsettings.h" #include "systeminfo.h" +#include "Logger.h" TTSSapi::TTSSapi(QObject* parent) : TTSBase(parent) { @@ -89,7 +90,7 @@ void TTSSapi::saveSettings() void TTSSapi::updateVoiceList() { - qDebug() << "[TTSSapi] updating voicelist"; + LOG_INFO() << "updating voicelist"; QStringList voiceList = getVoiceList(getSetting(eLANGUAGE)->current().toString()); getSetting(eVOICE)->setList(voiceList); if(voiceList.size() > 0) getSetting(eVOICE)->setCurrent(voiceList.at(0)); @@ -122,15 +123,15 @@ bool TTSSapi::start(QString *errStr) execstring.replace("%voice",m_TTSVoice); execstring.replace("%speed",m_TTSSpeed); - qDebug() << "[TTSSapi] Start:" << execstring; + LOG_INFO() << "Start:" << execstring; voicescript = new QProcess(NULL); //connect(voicescript,SIGNAL(readyReadStandardError()),this,SLOT(error())); voicescript->start(execstring); - qDebug() << "[TTSSapi] wait for process"; + LOG_INFO() << "wait for process"; if(!voicescript->waitForStarted()) { *errStr = tr("Could not start SAPI process"); - qDebug() << "[TTSSapi] starting process timed out!"; + LOG_ERROR() << "starting process timed out!"; return false; } @@ -161,7 +162,7 @@ QString TTSSapi::voiceVendor(void) while((vendor = voicestream->readLine()).isEmpty()) QCoreApplication::processEvents(); - qDebug() << "[TTSSAPI] TTS vendor:" << vendor; + LOG_INFO() << "TTS vendor:" << vendor; if(!keeprunning) { stop(); } @@ -184,12 +185,12 @@ QStringList TTSSapi::getVoiceList(QString language) execstring.replace("%exe",m_TTSexec); execstring.replace("%lang",language); - qDebug() << "[TTSSapi] Start:" << execstring; + LOG_INFO() << "Start:" << execstring; voicescript = new QProcess(NULL); voicescript->start(execstring); - qDebug() << "[TTSSapi] wait for process"; + LOG_INFO() << "wait for process"; if(!voicescript->waitForStarted()) { - qDebug() << "[TTSSapi] process startup timed out!"; + LOG_INFO() << "process startup timed out!"; return result; } voicescript->closeWriteChannel(); @@ -197,7 +198,7 @@ QStringList TTSSapi::getVoiceList(QString language) QString dataRaw = voicescript->readAllStandardError().data(); if(dataRaw.startsWith("Error")) { - qDebug() << "[TTSSapi] Error:" << dataRaw; + LOG_INFO() << "Error:" << dataRaw; } result = dataRaw.split(";",QString::SkipEmptyParts); if(result.size() > 0) @@ -226,7 +227,7 @@ TTSStatus TTSSapi::voice(QString text,QString wavfile, QString *errStr) { (void) errStr; QString query = "SPEAK\t"+wavfile+"\t"+text; - qDebug() << "[TTSSapi] voicing" << query; + LOG_INFO() << "voicing" << query; // append newline to query. Done now to keep debug output more readable. query.append("\r\n"); *voicestream << query; @@ -236,7 +237,7 @@ TTSStatus TTSSapi::voice(QString text,QString wavfile, QString *errStr) voicescript->waitForReadyRead(); if(!QFileInfo(wavfile).isFile()) { - qDebug() << "[TTSSapi] output file does not exist:" << wavfile; + LOG_ERROR() << "output file does not exist:" << wavfile; return FatalError; } return NoError; diff --git a/rbutil/rbutilqt/base/uninstall.cpp b/rbutil/rbutilqt/base/uninstall.cpp index ef6eb61ca5..498edbb057 100644 --- a/rbutil/rbutilqt/base/uninstall.cpp +++ b/rbutil/rbutilqt/base/uninstall.cpp @@ -19,6 +19,7 @@ #include #include "uninstall.h" #include "utils.h" +#include "Logger.h" Uninstaller::Uninstaller(QObject* parent,QString mountpoint): QObject(parent) { @@ -66,7 +67,7 @@ void Uninstaller::uninstall(void) if(installlog.contains(toDeleteList.at(j))) { deleteFile = false; - qDebug() << "[Uninstaller] file still in use:" << toDeleteList.at(j); + LOG_INFO() << "file still in use:" << toDeleteList.at(j); } installlog.endGroup(); } @@ -79,7 +80,7 @@ void Uninstaller::uninstall(void) emit logItem(tr("Could not delete %1") .arg(toDelete.filePath()), LOGWARNING); installlog.remove(toDeleteList.at(j)); - qDebug() << "[Uninstaller] deleted:" << toDelete.filePath(); + LOG_INFO() << "deleted:" << toDelete.filePath(); } else // if it is a dir, remember it for later deletion { diff --git a/rbutil/rbutilqt/base/utils.cpp b/rbutil/rbutilqt/base/utils.cpp index 1aeea7f18c..6a817e86da 100644 --- a/rbutil/rbutilqt/base/utils.cpp +++ b/rbutil/rbutilqt/base/utils.cpp @@ -21,6 +21,7 @@ #include "system.h" #include "rbsettings.h" #include "systeminfo.h" +#include "Logger.h" #ifdef UNICODE #define _UNICODE @@ -125,7 +126,7 @@ QString Utils::resolvePathCase(QString path) else return QString(""); } - qDebug() << "[Utils] resolving path" << path << "->" << realpath; + LOG_INFO() << "resolving path" << path << "->" << realpath; return realpath; } @@ -179,7 +180,7 @@ QString Utils::filesystemName(QString path) } while(result == noErr); #endif - qDebug() << "[Utils] Volume name of" << path << "is" << name; + LOG_INFO() << "Volume name of" << path << "is" << name; return name; } @@ -190,7 +191,7 @@ QString Utils::filesystemName(QString path) qulonglong Utils::filesystemFree(QString path) { qulonglong size = filesystemSize(path, FilesystemFree); - qDebug() << "[Utils] free disk space for" << path << size; + LOG_INFO() << "free disk space for" << path << size; return size; } @@ -198,7 +199,7 @@ qulonglong Utils::filesystemFree(QString path) qulonglong Utils::filesystemTotal(QString path) { qulonglong size = filesystemSize(path, FilesystemTotal); - qDebug() << "[Utils] total disk space for" << path << size; + LOG_INFO() << "total disk space for" << path << size; return size; } @@ -206,7 +207,7 @@ qulonglong Utils::filesystemTotal(QString path) qulonglong Utils::filesystemClusterSize(QString path) { qulonglong size = filesystemSize(path, FilesystemClusterSize); - qDebug() << "[Utils] cluster size for" << path << size; + LOG_INFO() << "cluster size for" << path << size; return size; } @@ -273,7 +274,7 @@ QString Utils::findExecutable(QString name) #elif defined(Q_OS_WIN) QStringList path = QString(getenv("PATH")).split(";", QString::SkipEmptyParts); #endif - qDebug() << "[Utils] system path:" << path; + LOG_INFO() << "system path:" << path; for(int i = 0; i < path.size(); i++) { QString executable = QDir::fromNativeSeparators(path.at(i)) + "/" + name; @@ -284,11 +285,11 @@ QString Utils::findExecutable(QString name) #endif if(QFileInfo(executable).isExecutable()) { - qDebug() << "[Utils] findExecutable: found" << executable; + LOG_INFO() << "findExecutable: found" << executable; return QDir::toNativeSeparators(executable); } } - qDebug() << "[Utils] findExecutable: could not find" << name; + LOG_INFO() << "findExecutable: could not find" << name; return ""; } @@ -299,7 +300,7 @@ QString Utils::findExecutable(QString name) */ QString Utils::checkEnvironment(bool permission) { - qDebug() << "[Utils] checking environment"; + LOG_INFO() << "checking environment"; QString text = ""; // check permission @@ -338,7 +339,7 @@ QString Utils::checkEnvironment(bool permission) */ int Utils::compareVersionStrings(QString s1, QString s2) { - qDebug() << "[Utils] comparing version strings" << s1 << "and" << s2; + LOG_INFO() << "comparing version strings" << s1 << "and" << s2; QString a = s1.trimmed(); QString b = s2.trimmed(); // if strings are identical return 0. @@ -418,7 +419,7 @@ int Utils::compareVersionStrings(QString s1, QString s2) */ QString Utils::resolveDevicename(QString path) { - qDebug() << "[Utils] resolving device name" << path; + LOG_INFO() << "resolving device name" << path; #if defined(Q_OS_LINUX) FILE *mn = setmntent("/etc/mtab", "r"); if(!mn) @@ -434,7 +435,7 @@ QString Utils::resolveDevicename(QString path) && (QString(ent->mnt_type).contains("vfat", Qt::CaseInsensitive) || QString(ent->mnt_type).contains("hfs", Qt::CaseInsensitive))) { endmntent(mn); - qDebug() << "[Utils] device name is" << ent->mnt_fsname; + LOG_INFO() << "device name is" << ent->mnt_fsname; return QString(ent->mnt_fsname); } } @@ -453,7 +454,7 @@ QString Utils::resolveDevicename(QString path) if(QString(mntinf->f_mntonname) == path && (QString(mntinf->f_fstypename).contains("msdos", Qt::CaseInsensitive) || QString(mntinf->f_fstypename).contains("hfs", Qt::CaseInsensitive))) { - qDebug() << "[Utils] device name is" << mntinf->f_mntfromname; + LOG_INFO() << "device name is" << mntinf->f_mntfromname; return QString(mntinf->f_mntfromname); } mntinf++; @@ -471,17 +472,17 @@ QString Utils::resolveDevicename(QString path) h = CreateFile(uncpath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if(h == INVALID_HANDLE_VALUE) { - //qDebug() << "error getting extents for" << uncpath; + //LOG_INFO() << "error getting extents for" << uncpath; return ""; } // get the extents if(DeviceIoControl(h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, extents, sizeof(buffer), &written, NULL)) { if(extents->NumberOfDiskExtents > 1) { - qDebug() << "[Utils] resolving device name: volume spans multiple disks!"; + LOG_INFO() << "resolving device name: volume spans multiple disks!"; return ""; } - qDebug() << "[Utils] device name is" << extents->Extents[0].DiskNumber; + LOG_INFO() << "device name is" << extents->Extents[0].DiskNumber; return QString("%1").arg(extents->Extents[0].DiskNumber); } #endif @@ -496,7 +497,7 @@ QString Utils::resolveDevicename(QString path) */ QString Utils::resolveMountPoint(QString device) { - qDebug() << "[Utils] resolving mountpoint:" << device; + LOG_INFO() << "resolving mountpoint:" << device; #if defined(Q_OS_LINUX) FILE *mn = setmntent("/etc/mtab", "r"); @@ -511,11 +512,11 @@ QString Utils::resolveMountPoint(QString device) QString result; if(QString(ent->mnt_type).contains("vfat", Qt::CaseInsensitive) || QString(ent->mnt_type).contains("hfs", Qt::CaseInsensitive)) { - qDebug() << "[Utils] resolved mountpoint is:" << ent->mnt_dir; + LOG_INFO() << "resolved mountpoint is:" << ent->mnt_dir; result = QString(ent->mnt_dir); } else { - qDebug() << "[Utils] mountpoint is wrong filesystem!"; + LOG_INFO() << "mountpoint is wrong filesystem!"; } endmntent(mn); return result; @@ -536,11 +537,11 @@ QString Utils::resolveMountPoint(QString device) if(QString(mntinf->f_mntfromname) == device) { if(QString(mntinf->f_fstypename).contains("msdos", Qt::CaseInsensitive) || QString(mntinf->f_fstypename).contains("hfs", Qt::CaseInsensitive)) { - qDebug() << "[Utils] resolved mountpoint is:" << mntinf->f_mntonname; + LOG_INFO() << "resolved mountpoint is:" << mntinf->f_mntonname; return QString(mntinf->f_mntonname); } else { - qDebug() << "[Utils] mountpoint is wrong filesystem!"; + LOG_INFO() << "mountpoint is wrong filesystem!"; return QString(); } } @@ -556,14 +557,14 @@ QString Utils::resolveMountPoint(QString device) for(letter = 'A'; letter <= 'Z'; letter++) { if(resolveDevicename(QString(letter)).toUInt() == driveno) { result = letter; - qDebug() << "[Utils] resolved mountpoint is:" << result; + LOG_INFO() << "resolved mountpoint is:" << result; break; } } if(!result.isEmpty()) return result + ":/"; #endif - qDebug() << "[Utils] resolving mountpoint failed!"; + LOG_INFO() << "resolving mountpoint failed!"; return QString(""); } @@ -589,11 +590,11 @@ QStringList Utils::mountpoints(enum MountpointsFilter type) QString fstype = QString::fromWCharArray(t); if(type == MountpointsAll || supported.contains(fstype)) { tempList << list.at(i).absolutePath(); - qDebug() << "[Utils] Added:" << list.at(i).absolutePath() + LOG_INFO() << "Added:" << list.at(i).absolutePath() << "type" << fstype; } else { - qDebug() << "[Utils] Ignored:" << list.at(i).absolutePath() + LOG_INFO() << "Ignored:" << list.at(i).absolutePath() << "type" << fstype; } } @@ -607,11 +608,11 @@ QStringList Utils::mountpoints(enum MountpointsFilter type) while(num--) { if(type == MountpointsAll || supported.contains(mntinf->f_fstypename)) { tempList << QString(mntinf->f_mntonname); - qDebug() << "[Utils] Added:" << mntinf->f_mntonname + LOG_INFO() << "Added:" << mntinf->f_mntonname << "is" << mntinf->f_mntfromname << "type" << mntinf->f_fstypename; } else { - qDebug() << "[Utils] Ignored:" << mntinf->f_mntonname + LOG_INFO() << "Ignored:" << mntinf->f_mntonname << "is" << mntinf->f_mntfromname << "type" << mntinf->f_fstypename; } mntinf++; @@ -626,11 +627,11 @@ QStringList Utils::mountpoints(enum MountpointsFilter type) while((ent = getmntent(mn))) { if(type == MountpointsAll || supported.contains(ent->mnt_type)) { tempList << QString(ent->mnt_dir); - qDebug() << "[Utils] Added:" << ent->mnt_dir + LOG_INFO() << "Added:" << ent->mnt_dir << "is" << ent->mnt_fsname << "type" << ent->mnt_type; } else { - qDebug() << "[Utils] Ignored:" << ent->mnt_dir + LOG_INFO() << "Ignored:" << ent->mnt_dir << "is" << ent->mnt_fsname << "type" << ent->mnt_type; } } @@ -658,13 +659,13 @@ QStringList Utils::findRunningProcess(QStringList names) hdl = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(hdl == INVALID_HANDLE_VALUE) { - qDebug() << "[Utils] CreateToolhelp32Snapshot failed."; + LOG_ERROR() << "CreateToolhelp32Snapshot failed."; return found; } entry.dwSize = sizeof(PROCESSENTRY32); entry.szExeFile[0] = '\0'; if(!Process32First(hdl, &entry)) { - qDebug() << "[Utils] Process32First failed."; + LOG_ERROR() << "Process32First failed."; return found; } @@ -721,7 +722,7 @@ QStringList Utils::findRunningProcess(QStringList names) found.append(processlist.at(index)); } } - qDebug() << "[Utils] Found listed processes running:" << found; + LOG_INFO() << "Found listed processes running:" << found; return found; } diff --git a/rbutil/rbutilqt/base/voicefile.cpp b/rbutil/rbutilqt/base/voicefile.cpp index 70c0f7b653..814ac538e2 100644 --- a/rbutil/rbutilqt/base/voicefile.cpp +++ b/rbutil/rbutilqt/base/voicefile.cpp @@ -23,6 +23,7 @@ #include "rbsettings.h" #include "systeminfo.h" #include "ziputil.h" +#include "Logger.h" VoiceFileCreator::VoiceFileCreator(QObject* parent) :QObject(parent) { @@ -65,7 +66,7 @@ bool VoiceFileCreator::createVoiceFile() // check if voicefile is present on target QString fn = m_mountpoint + "/.rockbox/langs/voicestrings.zip"; - qDebug() << "[VoiceFile] searching for zipped voicestrings at" << fn; + LOG_INFO() << "searching for zipped voicestrings at" << fn; if(QFileInfo(fn).isFile()) { // search for binary voice strings file in archive ZipUtil z(this); @@ -79,7 +80,7 @@ bool VoiceFileCreator::createVoiceFile() } } if(index < contents.size()) { - qDebug() << "[VoiceFile] extracting strings file from zip"; + LOG_INFO() << "extracting strings file from zip"; // extract strings QTemporaryFile stringsfile; stringsfile.open(); @@ -153,7 +154,7 @@ bool VoiceFileCreator::createVoiceFile() genlang.replace("%REVISION%", version); genlang.replace("%FEATURES%", features); QUrl genlangUrl(genlang); - qDebug() << "[VoiceFileCreator] downloading" << genlangUrl; + LOG_INFO() << "downloading" << genlangUrl; //download the correct genlang output QTemporaryFile *downloadFile = new QTemporaryFile(this); @@ -175,7 +176,7 @@ bool VoiceFileCreator::createVoiceFile() void VoiceFileCreator::downloadDone(bool error) { - qDebug() << "[VoiceFileCreator] download done, error:" << error; + LOG_INFO() << "download done, error:" << error; // update progress bar emit logProgress(1,1); @@ -253,7 +254,7 @@ void VoiceFileCreator::create(void) m_talkList.append(entry); } else if(entry.toSpeak.isEmpty()) { - qDebug() << "[Voicefile] Empty voice string for ID" << id; + LOG_WARNING() << "Empty voice string for ID" << id; } else { m_talkList.append(entry); @@ -314,7 +315,7 @@ void VoiceFileCreator::create(void) return; } - qDebug() << "[VoiceFile] Running voicefont, format" << m_voiceformat; + LOG_INFO() << "Running voicefont, format" << m_voiceformat; voicefont(ids2,m_targetid,m_path.toLocal8Bit().data(), output, m_voiceformat); // ids2 and output are closed by voicefont(). diff --git a/rbutil/rbutilqt/base/zipinstaller.cpp b/rbutil/rbutilqt/base/zipinstaller.cpp index e24199408e..b2c8e09178 100644 --- a/rbutil/rbutilqt/base/zipinstaller.cpp +++ b/rbutil/rbutilqt/base/zipinstaller.cpp @@ -20,6 +20,7 @@ #include "zipinstaller.h" #include "utils.h" #include "ziputil.h" +#include "Logger.h" ZipInstaller::ZipInstaller(QObject* parent): QObject(parent) { @@ -31,7 +32,7 @@ ZipInstaller::ZipInstaller(QObject* parent): QObject(parent) void ZipInstaller::install() { - qDebug() << "[ZipInstall] initializing installation"; + LOG_INFO() << "initializing installation"; runner = 0; connect(this, SIGNAL(cont()), this, SLOT(installContinue())); @@ -44,17 +45,17 @@ void ZipInstaller::install() void ZipInstaller::abort() { - qDebug() << "[ZipInstall] Aborted"; + LOG_INFO() << "Aborted"; emit internalAborted(); } void ZipInstaller::installContinue() { - qDebug() << "[ZipInstall] continuing installation"; + LOG_INFO() << "continuing installation"; runner++; // this gets called when a install finished, so increase first. - qDebug() << "[ZipInstall] runner done:" << runner << "/" << m_urllist.size(); + LOG_INFO() << "runner done:" << runner << "/" << m_urllist.size(); if(runner < m_urllist.size()) { emit logItem(tr("done."), LOGOK); m_url = m_urllist.at(runner); @@ -74,7 +75,7 @@ void ZipInstaller::installContinue() void ZipInstaller::installStart() { - qDebug() << "[ZipInstall] starting installation"; + LOG_INFO() << "starting installation"; emit logItem(tr("Downloading file %1.%2").arg(QFileInfo(m_url).baseName(), QFileInfo(m_url).completeSuffix()),LOGINFO); @@ -105,7 +106,7 @@ void ZipInstaller::installStart() void ZipInstaller::downloadDone(bool error) { - qDebug() << "[ZipInstall] download done, error:" << error; + LOG_INFO() << "download done, error:" << error; QStringList zipContents; // needed later // update progress bar @@ -127,7 +128,7 @@ void ZipInstaller::downloadDone(bool error) QCoreApplication::processEvents(); if(m_unzip) { // unzip downloaded file - qDebug() << "[ZipInstall] about to unzip " << m_file << "to" << m_mountpoint; + LOG_INFO() << "about to unzip" << m_file << "to" << m_mountpoint; emit logItem(tr("Extracting file."), LOGINFO); QCoreApplication::processEvents(); @@ -159,7 +160,7 @@ void ZipInstaller::downloadDone(bool error) else { // only copy the downloaded file to the output location / name emit logItem(tr("Installing file."), LOGINFO); - qDebug() << "[ZipInstall] saving downloaded file (no extraction)"; + LOG_INFO() << "saving downloaded file (no extraction)"; m_downloadFile->open(); // copy fails if file is not opened (filename issue?) // make sure the required path is existing diff --git a/rbutil/rbutilqt/base/zipinstaller.h b/rbutil/rbutilqt/base/zipinstaller.h index 4ea08fbe53..97a5156ee8 100644 --- a/rbutil/rbutilqt/base/zipinstaller.h +++ b/rbutil/rbutilqt/base/zipinstaller.h @@ -26,6 +26,7 @@ #include "progressloggerinterface.h" #include "httpget.h" +#include "Logger.h" class ZipInstaller : public QObject { @@ -40,9 +41,9 @@ public: void setLogSection(QString name) {m_loglist = QStringList(name);} void setLogSection(QStringList name) { m_loglist = name; } void setLogVersion(QString v = "") - { m_verlist = QStringList(v); qDebug() << m_verlist;} + { m_verlist = QStringList(v); LOG_INFO() << m_verlist;} void setLogVersion(QStringList v) - { m_verlist = v; qDebug() << m_verlist;} + { m_verlist = v; LOG_INFO() << m_verlist;} void setUnzip(bool i) { m_unzip = i; } void setTarget(QString t) { m_target = t; } void setCache(QDir c) { m_cache = c; m_usecache = true; }; diff --git a/rbutil/rbutilqt/base/ziputil.cpp b/rbutil/rbutilqt/base/ziputil.cpp index b93d5fd86a..b6cfdddce2 100644 --- a/rbutil/rbutilqt/base/ziputil.cpp +++ b/rbutil/rbutilqt/base/ziputil.cpp @@ -20,6 +20,7 @@ #include #include "ziputil.h" #include "progressloggerinterface.h" +#include "Logger.h" #include "quazip/quazip.h" #include "quazip/quazipfile.h" @@ -76,7 +77,7 @@ bool ZipUtil::close(void) //! @return true on success, false otherwise bool ZipUtil::extractArchive(const QString& dest, QString file) { - qDebug() << "[ZipUtil] extractArchive" << dest << file; + LOG_INFO() << "extractArchive" << dest << file; bool result = true; if(!m_zip) { return false; @@ -122,15 +123,15 @@ bool ZipUtil::extractArchive(const QString& dest, QString file) if(!QDir().mkpath(QFileInfo(outfilename).absolutePath())) { result = false; emit logItem(tr("Creating output path failed"), LOGERROR); - qDebug() << "[ZipUtil] creating output path failed for:" - << outfilename; + LOG_INFO() << "creating output path failed for:" + << outfilename; break; } if(!outputFile.open(QFile::WriteOnly)) { result = false; emit logItem(tr("Creating output file failed"), LOGERROR); - qDebug() << "[ZipUtil] creating output file failed:" - << outfilename; + LOG_INFO() << "creating output file failed:" + << outfilename; break; } currentFile->open(QIODevice::ReadOnly); @@ -138,8 +139,8 @@ bool ZipUtil::extractArchive(const QString& dest, QString file) if(currentFile->getZipError() != UNZ_OK) { result = false; emit logItem(tr("Error during Zip operation"), LOGERROR); - qDebug() << "[ZipUtil] QuaZip error:" << currentFile->getZipError() - << "on file" << currentFile->getFileName(); + LOG_INFO() << "QuaZip error:" << currentFile->getZipError() + << "on file" << currentFile->getFileName(); break; } currentFile->close(); @@ -162,7 +163,7 @@ bool ZipUtil::appendDirToArchive(QString& source, QString& basedir) { bool result = true; if(!m_zip || !m_zip->isOpen()) { - qDebug() << "[ZipUtil] Zip file not open!"; + LOG_INFO() << "Zip file not open!"; return false; } // get a list of all files and folders. Needed for progress info and avoids @@ -176,14 +177,14 @@ bool ZipUtil::appendDirToArchive(QString& source, QString& basedir) fileList.append(iterator.filePath()); } } - qDebug() << "[ZipUtil] Adding" << fileList.size() << "files to archive"; + LOG_INFO() << "Adding" << fileList.size() << "files to archive"; int max = fileList.size(); for(int i = 0; i < max; i++) { QString current = fileList.at(i); if(!appendFileToArchive(current, basedir)) { - qDebug() << "[ZipUtil] Error appending file" << current - << "to archive" << m_zip->getZipName(); + LOG_ERROR() << "Error appending file" << current + << "to archive" << m_zip->getZipName(); result = false; break; } @@ -199,7 +200,7 @@ bool ZipUtil::appendFileToArchive(QString& file, QString& basedir) { bool result = true; if(!m_zip || !m_zip->isOpen()) { - qDebug() << "[ZipUtil] Zip file not open!"; + LOG_ERROR() << "Zip file not open!"; return false; } // skip folders, we can't add them. @@ -215,12 +216,12 @@ bool ZipUtil::appendFileToArchive(QString& file, QString& basedir) QFile fin(file); if(!fin.open(QFile::ReadOnly)) { - qDebug() << "[ZipUtil] Could not open file for reading:" << file; + LOG_ERROR() << "Could not open file for reading:" << file; return false; } if(!fout.open(QIODevice::WriteOnly, QuaZipNewInfo(newfile, infile))) { fin.close(); - qDebug() << "[ZipUtil] Could not open file for writing:" << newfile; + LOG_ERROR() << "Could not open file for writing:" << newfile; return false; } @@ -253,11 +254,11 @@ qint64 ZipUtil::totalUncompressedSize(unsigned int clustersize) } } if(clustersize > 0) { - qDebug() << "[ZipUtil] calculation rounded to cluster size for each file:" - << clustersize; + LOG_INFO() << "calculation rounded to cluster size for each file:" + << clustersize; } - qDebug() << "[ZipUtil] size of archive files uncompressed:" - << uncompressed; + LOG_INFO() << "size of archive files uncompressed:" + << uncompressed; return uncompressed; } @@ -281,7 +282,7 @@ QList ZipUtil::contentProperties() { QList items; if(!m_zip || !m_zip->isOpen()) { - qDebug() << "[ZipUtil] Zip file not open!"; + LOG_ERROR() << "Zip file not open!"; return items; } QuaZipFileInfo info; @@ -290,8 +291,8 @@ QList ZipUtil::contentProperties() { currentFile.getFileInfo(&info); if(currentFile.getZipError() != UNZ_OK) { - qDebug() << "[ZipUtil] QuaZip error:" << currentFile.getZipError() - << "on file" << currentFile.getFileName(); + LOG_ERROR() << "QuaZip error:" << currentFile.getZipError() + << "on file" << currentFile.getFileName(); return QList(); } items.append(info); diff --git a/rbutil/rbutilqt/changelog.txt b/rbutil/rbutilqt/changelog.txt index 35c5322dc9..7b3bef6cb9 100644 --- a/rbutil/rbutilqt/changelog.txt +++ b/rbutil/rbutilqt/changelog.txt @@ -13,5 +13,6 @@ Version 1.4 * Save proxy password differently in configuration file (better solution for FS#12166). * Add support for building Rockbox Utility with Qt5. * Add Changelog window. +* Rework System Trace functionality. diff --git a/rbutil/rbutilqt/configure.cpp b/rbutil/rbutilqt/configure.cpp index 456e65cdd9..5a78c6f6a1 100644 --- a/rbutil/rbutilqt/configure.cpp +++ b/rbutil/rbutilqt/configure.cpp @@ -47,6 +47,7 @@ #include "rbutilqt.h" #include "systrace.h" +#include "Logger.h" #define DEFAULT_LANG "English (en)" #define DEFAULT_LANG_CODE "en" @@ -125,7 +126,7 @@ Config::Config(QWidget *parent,int index) : QDialog(parent) void Config::accept() { - qDebug() << "[Config] checking configuration"; + LOG_INFO() << "checking configuration"; QString errormsg = tr("The following errors occurred:") + "
    "; bool error = false; @@ -154,7 +155,7 @@ void Config::accept() QUrl p = proxy; p.setPassword(proxy.password().toUtf8().toBase64()); RbSettings::setValue(RbSettings::Proxy, p.toString()); - qDebug() << "[Config] setting proxy to:" << proxy.toString(QUrl::RemovePassword); + LOG_INFO() << "setting proxy to:" << proxy.toString(QUrl::RemovePassword); // proxy type QString proxyType; if(ui.radioNoProxy->isChecked()) proxyType = "none"; @@ -240,7 +241,7 @@ void Config::accept() void Config::abort() { - qDebug() << "[Config] aborted."; + LOG_INFO() << "aborted."; this->close(); } @@ -334,7 +335,7 @@ void Config::showProxyPassword(bool show) void Config::showDisabled(bool show) { - qDebug() << "[Config] disabled targets shown:" << show; + LOG_INFO() << "disabled targets shown:" << show; if(show) QMessageBox::warning(this, tr("Showing disabled targets"), tr("You just enabled showing targets that are marked disabled. " @@ -349,7 +350,7 @@ void Config::setDevices() { // setup devices table - qDebug() << "[Config] setting up devices list"; + LOG_INFO() << "setting up devices list"; QStringList platformList; if(ui.showDisabled->isChecked()) @@ -393,7 +394,7 @@ void Config::setDevices() SystemInfo::CurName).toString() + " (" +ServerInfo::platformValue(platformList.at(it), ServerInfo::CurStatus).toString() +")"; - qDebug() << "[Config] add supported device:" << brands.at(c) << curname; + LOG_INFO() << "add supported device:" << brands.at(c) << curname; w2 = new QTreeWidgetItem(w, QStringList(curname)); w2->setData(0, Qt::UserRole, platformList.at(it)); @@ -516,7 +517,7 @@ void Config::setSystemProxy(bool checked) proxy.setPort(ui.proxyPort->text().toInt()); // show system values in input box QUrl envproxy = System::systemProxy(); - qDebug() << "[Config] setting system proxy" << envproxy; + LOG_INFO() << "setting system proxy" << envproxy; ui.proxyHost->setText(envproxy.host()); ui.proxyPort->setText(QString("%1").arg(envproxy.port())); @@ -524,7 +525,7 @@ void Config::setSystemProxy(bool checked) ui.proxyPass->setText(envproxy.password()); if(envproxy.host().isEmpty() || envproxy.port() == -1) { - qDebug() << "[Config] sytem proxy is invalid."; + LOG_WARNING() << "system proxy is invalid."; QMessageBox::warning(this, tr("Proxy Detection"), tr("The System Proxy settings are invalid!\n" "Rockbox Utility can't work with this proxy settings. " @@ -571,7 +572,7 @@ QStringList Config::findLanguageFiles() langs.append(a); } langs.sort(); - qDebug() << "[Config] available lang files:" << langs; + LOG_INFO() << "available lang files:" << langs; return langs; } @@ -592,7 +593,7 @@ QString Config::languageName(const QString &qmFile) void Config::updateLanguage() { - qDebug() << "[Config] update selected language"; + LOG_INFO() << "update selected language"; // remove all old translators for(int i = 0; i < RbUtilQt::translators.size(); ++i) { @@ -603,7 +604,7 @@ void Config::updateLanguage() QList a = ui.listLanguages->selectedItems(); if(a.size() > 0) language = lang.value(a.at(0)->text()); - qDebug() << "[Config] new language:" << language; + LOG_INFO() << "new language:" << language; QString applang = QLocale::system().name(); QTranslator *translator = new QTranslator(qApp); @@ -668,7 +669,7 @@ void Config::refreshMountpoint() ui.mountPoint->addItem(QDir::toNativeSeparators(mps.at(i)), description); } else { - qDebug() << "[Config] mountpoint not writable, skipping:" << mps.at(i); + LOG_WARNING() << "mountpoint not writable, skipping:" << mps.at(i); } } if(!mountpoint.isEmpty()) { @@ -682,7 +683,7 @@ void Config::updateMountpoint(QString m) { if(!m.isEmpty()) { mountpoint = QDir::fromNativeSeparators(m); - qDebug() << "[Config] Mountpoint set to" << mountpoint; + LOG_INFO() << "Mountpoint set to" << mountpoint; } } @@ -695,7 +696,7 @@ void Config::updateMountpoint(int idx) QString mp = ui.mountPoint->itemText(idx); if(!mp.isEmpty()) { mountpoint = QDir::fromNativeSeparators(mp); - qDebug() << "[Config] Mountpoint set to" << mountpoint; + LOG_INFO() << "Mountpoint set to" << mountpoint; } } @@ -715,7 +716,7 @@ void Config::setMountpoint(QString m) ui.mountPoint->addItem(QDir::toNativeSeparators(m)); ui.mountPoint->setCurrentIndex(ui.mountPoint->findText(m)); } - qDebug() << "[Config] Mountpoint set to" << mountpoint; + LOG_INFO() << "Mountpoint set to" << mountpoint; } diff --git a/rbutil/rbutilqt/createvoicewindow.cpp b/rbutil/rbutilqt/createvoicewindow.cpp index f008c31f7b..b56ffdb2c7 100644 --- a/rbutil/rbutilqt/createvoicewindow.cpp +++ b/rbutil/rbutilqt/createvoicewindow.cpp @@ -23,6 +23,7 @@ #include "configure.h" #include "rbsettings.h" #include "systeminfo.h" +#include "Logger.h" CreateVoiceWindow::CreateVoiceWindow(QWidget *parent) : QDialog(parent) { @@ -88,7 +89,7 @@ void CreateVoiceWindow::updateSettings(void) f = languages.value(uilang).at(0); } sel = ui.comboLanguage->findData(f); - qDebug() << "[CreateVoiceWindow] Selected language index:" << sel; + LOG_INFO() << "Selected language index:" << sel; } ui.comboLanguage->setCurrentIndex(sel); diff --git a/rbutil/rbutilqt/encttscfggui.cpp b/rbutil/rbutilqt/encttscfggui.cpp index 6a51869318..54ec4bc67a 100644 --- a/rbutil/rbutilqt/encttscfggui.cpp +++ b/rbutil/rbutilqt/encttscfggui.cpp @@ -32,6 +32,7 @@ #include #include #include "encttscfggui.h" +#include "Logger.h" EncTtsCfgGui::EncTtsCfgGui(QDialog* parent, EncTtsSettingInterface* iface, QString name) : QDialog(parent) @@ -174,7 +175,7 @@ QWidget* EncTtsCfgGui::createWidgets(EncTtsSetting* setting) } default: { - qDebug() << "Warning: unknown EncTTsSetting type" << setting->type(); + LOG_WARNING() << "Warning: unknown EncTTsSetting type" << setting->type(); break; } } @@ -252,7 +253,7 @@ void EncTtsCfgGui::updateSetting() } default: { - qDebug() << "unknown Settingtype !!"; + LOG_WARNING() << "unknown setting type!"; break; } } @@ -331,7 +332,7 @@ void EncTtsCfgGui::updateWidget() } default: { - qDebug() << "unknown EncTTsSetting"; + LOG_WARNING() << "unknown EncTTsSetting"; break; } } diff --git a/rbutil/rbutilqt/gui/backupdialog.cpp b/rbutil/rbutilqt/gui/backupdialog.cpp index 1571ae9191..f12c47b570 100644 --- a/rbutil/rbutilqt/gui/backupdialog.cpp +++ b/rbutil/rbutilqt/gui/backupdialog.cpp @@ -26,6 +26,7 @@ #include "progressloggergui.h" #include "ziputil.h" #include "rockboxinfo.h" +#include "Logger.h" class BackupSizeThread : public QThread { @@ -42,14 +43,14 @@ class BackupSizeThread : public QThread void BackupSizeThread::run(void) { - qDebug() << "BackupSizeThread] Thread started, calculating" << m_path; + LOG_INFO() << "Thread started, calculating" << m_path; m_currentSize = 0; QDirIterator it(m_path, QDirIterator::Subdirectories); while(it.hasNext()) { m_currentSize += QFileInfo(it.next()).size(); } - qDebug() << "[BackupSizeThread] Thread done, sum:" << m_currentSize; + LOG_INFO() << "Thread done, sum:" << m_currentSize; } diff --git a/rbutil/rbutilqt/gui/infowidget.cpp b/rbutil/rbutilqt/gui/infowidget.cpp index bfc0742593..25b0503090 100644 --- a/rbutil/rbutilqt/gui/infowidget.cpp +++ b/rbutil/rbutilqt/gui/infowidget.cpp @@ -20,6 +20,7 @@ #include #include "infowidget.h" #include "rbsettings.h" +#include "Logger.h" InfoWidget::InfoWidget(QWidget *parent) : QWidget(parent) { @@ -35,7 +36,7 @@ InfoWidget::InfoWidget(QWidget *parent) : QWidget(parent) void InfoWidget::updateInfo(void) { - qDebug() << "[InfoWidget] updating server info"; + LOG_INFO() << "updating server info"; QString mp = RbSettings::value(RbSettings::Mountpoint).toString(); QSettings log(mp + "/.rockbox/rbutil.log", QSettings::IniFormat, this); diff --git a/rbutil/rbutilqt/gui/manualwidget.cpp b/rbutil/rbutilqt/gui/manualwidget.cpp index dc68e65460..0ba3012aea 100644 --- a/rbutil/rbutilqt/gui/manualwidget.cpp +++ b/rbutil/rbutilqt/gui/manualwidget.cpp @@ -24,6 +24,7 @@ #include "rbsettings.h" #include "serverinfo.h" #include "systeminfo.h" +#include "Logger.h" ManualWidget::ManualWidget(QWidget *parent) : QWidget(parent) { @@ -36,7 +37,7 @@ ManualWidget::ManualWidget(QWidget *parent) : QWidget(parent) void ManualWidget::updateManual() { - qDebug() << "[ManualWidget] updating manual URLs"; + LOG_INFO() << "updating manual URLs"; m_platform = RbSettings::value(RbSettings::Platform).toString(); if(!m_platform.isEmpty()) { diff --git a/rbutil/rbutilqt/gui/selectiveinstallwidget.cpp b/rbutil/rbutilqt/gui/selectiveinstallwidget.cpp index 96183d1075..35837ba41d 100644 --- a/rbutil/rbutilqt/gui/selectiveinstallwidget.cpp +++ b/rbutil/rbutilqt/gui/selectiveinstallwidget.cpp @@ -30,6 +30,7 @@ #include "bootloaderinstallhelper.h" #include "themesinstallwindow.h" #include "utils.h" +#include "Logger.h" SelectiveInstallWidget::SelectiveInstallWidget(QWidget* parent) : QWidget(parent) { @@ -147,7 +148,7 @@ void SelectiveInstallWidget::updateVersion(void) void SelectiveInstallWidget::saveSettings(void) { - qDebug() << "[SelectiveInstallWidget] saving current settings"; + LOG_INFO() << "saving current settings"; RbSettings::setValue(RbSettings::InstallRockbox, ui.rockboxCheckbox->isChecked()); RbSettings::setValue(RbSettings::InstallFonts, ui.fontsCheckbox->isChecked()); @@ -158,7 +159,7 @@ void SelectiveInstallWidget::saveSettings(void) void SelectiveInstallWidget::startInstall(void) { - qDebug() << "[SelectiveInstallWidget] starting installation"; + LOG_INFO() << "starting installation"; saveSettings(); m_installStage = 0; @@ -191,15 +192,15 @@ void SelectiveInstallWidget::startInstall(void) void SelectiveInstallWidget::continueInstall(bool error) { - qDebug() << "[SelectiveInstallWidget] continuing install with stage" << m_installStage; + LOG_INFO() << "continuing install with stage" << m_installStage; if(error) { - qDebug() << "[SelectiveInstallWidget] Last part returned error."; + LOG_ERROR() << "Last part returned error."; m_logger->setFinished(); m_installStage = 7; } m_installStage++; switch(m_installStage) { - case 0: qDebug() << "[SelectiveInstallWidget] Something wrong!"; break; + case 0: LOG_ERROR() << "Something wrong!"; break; case 1: installBootloader(); break; case 2: installRockbox(); break; case 3: installFonts(); break; @@ -210,7 +211,7 @@ void SelectiveInstallWidget::continueInstall(bool error) } if(m_installStage > 6) { - qDebug() << "[SelectiveInstallWidget] All install stages done."; + LOG_INFO() << "All install stages done."; m_logger->setFinished(); if(m_blmethod != "none") { // check if Rockbox is installed by looking after rockbox-info.txt. @@ -225,7 +226,7 @@ void SelectiveInstallWidget::continueInstall(bool error) void SelectiveInstallWidget::installBootloader(void) { if(ui.bootloaderCheckbox->isChecked()) { - qDebug() << "[SelectiveInstallWidget] installing bootloader"; + LOG_INFO() << "installing bootloader"; QString platform = RbSettings::value(RbSettings::Platform).toString(); QString backupDestination = ""; @@ -292,7 +293,7 @@ void SelectiveInstallWidget::installBootloader(void) if(!backupDestination.isEmpty()) backupDestination += "/" + targetFolder; - qDebug() << "[RbUtil] backing up to" << backupDestination; + LOG_INFO() << "backing up to" << backupDestination; // backup needs to be done after the m_logger has been set up. } } @@ -350,7 +351,7 @@ void SelectiveInstallWidget::installBootloader(void) } else { - qDebug() << "[SelectiveInstallWidget] Bootloader install disabled."; + LOG_INFO() << "Bootloader install disabled."; emit installSkipped(false); } } @@ -372,7 +373,7 @@ void SelectiveInstallWidget::installBootloaderPost() void SelectiveInstallWidget::installRockbox(void) { if(ui.rockboxCheckbox->isChecked()) { - qDebug() << "[SelectiveInstallWidget] installing Rockbox"; + LOG_INFO() << "installing Rockbox"; QString url; QString selected = ui.selectedVersion->itemData(ui.selectedVersion->currentIndex()).toString(); @@ -405,7 +406,7 @@ void SelectiveInstallWidget::installRockbox(void) } else { - qDebug() << "[SelectiveInstallWidget] Rockbox install disabled."; + LOG_INFO() << "Rockbox install disabled."; emit installSkipped(false); } } @@ -414,7 +415,7 @@ void SelectiveInstallWidget::installRockbox(void) void SelectiveInstallWidget::installFonts(void) { if(ui.fontsCheckbox->isChecked()) { - qDebug() << "[SelectiveInstallWidget] installing Fonts"; + LOG_INFO() << "installing Fonts"; RockboxInfo installInfo(m_mountpoint); QString fontsurl; @@ -447,7 +448,7 @@ void SelectiveInstallWidget::installFonts(void) m_zipinstaller->install(); } else { - qDebug() << "[SelectiveInstallWidget] Fonts install disabled."; + LOG_INFO() << "Fonts install disabled."; emit installSkipped(false); } } @@ -465,7 +466,7 @@ void SelectiveInstallWidget::customizeThemes(void) void SelectiveInstallWidget::installThemes(void) { if(ui.themesCheckbox->isChecked()) { - qDebug() << "[SelectiveInstallWidget] installing themes"; + LOG_INFO() << "installing themes"; if(m_themesinstaller == NULL) m_themesinstaller = new ThemesInstallWindow(this); @@ -475,7 +476,7 @@ void SelectiveInstallWidget::installThemes(void) m_themesinstaller->install(); } else { - qDebug() << "[SelectiveInstallWidget] Themes install disabled."; + LOG_INFO() << "Themes install disabled."; emit installSkipped(false); } } @@ -489,7 +490,7 @@ void SelectiveInstallWidget::installGamefiles(void) m_logger->addItem(tr("Your installation doesn't require game files, skipping."), LOGINFO); emit installSkipped(false); } - qDebug() << "[SelectiveInstallWidget] installing gamefiles"; + LOG_INFO() << "installing gamefiles"; // create new zip installer if(m_zipinstaller != NULL) m_zipinstaller->deleteLater(); m_zipinstaller = new ZipInstaller(this); @@ -507,7 +508,7 @@ void SelectiveInstallWidget::installGamefiles(void) m_zipinstaller->install(); } else { - qDebug() << "[SelectiveInstallWidget] Gamefile install disabled."; + LOG_INFO() << "Gamefile install disabled."; emit installSkipped(false); } } diff --git a/rbutil/rbutilqt/installtalkwindow.cpp b/rbutil/rbutilqt/installtalkwindow.cpp index db5bccabe9..d9f2cc7e98 100644 --- a/rbutil/rbutilqt/installtalkwindow.cpp +++ b/rbutil/rbutilqt/installtalkwindow.cpp @@ -23,6 +23,7 @@ #include "configure.h" #include "rbsettings.h" #include "systeminfo.h" +#include "Logger.h" InstallTalkWindow::InstallTalkWindow(QWidget *parent) : QDialog(parent) { @@ -118,8 +119,8 @@ void InstallTalkWindow::accept() connect(logger,SIGNAL(aborted()),talkcreator,SLOT(abort())); for(int i = 0; i < foldersToTalk.size(); i++) { - qDebug() << "[InstallTalkWindow] creating talk files for folder" - << foldersToTalk.at(i); + LOG_INFO() << "creating talk files for folder" + << foldersToTalk.at(i); talkcreator->setDir(foldersToTalk.at(i)); talkcreator->createTalkFiles(); } diff --git a/rbutil/rbutilqt/logger/AbstractAppender.cpp b/rbutil/rbutilqt/logger/AbstractAppender.cpp new file mode 100644 index 0000000000..de86b930d0 --- /dev/null +++ b/rbutil/rbutilqt/logger/AbstractAppender.cpp @@ -0,0 +1,58 @@ +/* + Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License version 2.1 + as published by the Free Software Foundation and appearing in the file + LICENSE.LGPL included in the packaging of this file. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. +*/ +// Local +#include "AbstractAppender.h" + +// Qt +#include + + +AbstractAppender::AbstractAppender() + : m_detailsLevel(Logger::Debug) +{} + + +AbstractAppender::~AbstractAppender() +{} + + +Logger::LogLevel AbstractAppender::detailsLevel() const +{ + QMutexLocker locker(&m_detailsLevelMutex); + return m_detailsLevel; +} + + +void AbstractAppender::setDetailsLevel(Logger::LogLevel level) +{ + QMutexLocker locker(&m_detailsLevelMutex); + m_detailsLevel = level; +} + + +void AbstractAppender::setDetailsLevel(const QString& level) +{ + setDetailsLevel(Logger::levelFromString(level)); +} + + +void AbstractAppender::write(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, + const char* function, const QString& message) +{ + if (logLevel >= detailsLevel()) + { + QMutexLocker locker(&m_writeMutex); + append(timeStamp, logLevel, file, line, function, message); + } +} diff --git a/rbutil/rbutilqt/logger/AbstractAppender.h b/rbutil/rbutilqt/logger/AbstractAppender.h new file mode 100644 index 0000000000..df1df4957c --- /dev/null +++ b/rbutil/rbutilqt/logger/AbstractAppender.h @@ -0,0 +1,125 @@ +/* + Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License version 2.1 + as published by the Free Software Foundation and appearing in the file + LICENSE.LGPL included in the packaging of this file. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. +*/ +#ifndef ABSTRACTAPPENDER_H +#define ABSTRACTAPPENDER_H + +// Local +#include "CuteLogger_global.h" +#include + +// Qt +#include + +//! The AbstractAppender class provides an abstract base class for writing a log entries. +/** + * The AbstractAppender class is the base interface class for all log appenders that could be used with Logger. + * + * AbstractAppender provides a common implementation for the thread safe, mutex-protected logging of application + * messages, such as ConsoleAppender, FileAppender or something else. AbstractAppender is abstract and can not be + * instantiated, but you can use any of its subclasses or create a custom log appender at your choice. + * + * Appenders are the logical devices that is aimed to be attached to Logger object by calling + * Logger::registerAppender(). On each log record call from the application Logger object sequentially calls write() + * function on all the appenders registered in it. + * + * You can subclass AbstractAppender to implement a logging target of any kind you like. It may be the external logging + * subsystem (for example, syslog in *nix), XML file, SQL database entries, D-Bus messages or anything else you can + * imagine. + * + * For the simple non-structured plain text logging (for example, to a plain text file or to the console output) you may + * like to subclass the AbstractStringAppender instead of AbstractAppender, which will give you a more convinient way to + * control the format of the log output. + * + * \sa AbstractStringAppender + * \sa Logger::registerAppender() + */ +class CUTELOGGERSHARED_EXPORT AbstractAppender +{ + public: + //! Constructs a AbstractAppender object. + AbstractAppender(); + + //! Destructs the AbstractAppender object. + virtual ~AbstractAppender(); + + //! Returns the current details level of appender. + /** + * Log records with a log level lower than a current detailsLevel() will be silently ignored by appender and would not + * be sent to its append() function. + * + * It provides additional logging flexibility, allowing you to set the different severity levels for different types + * of logs. + * + * \note This function is thread safe. + * + * \sa setDetailsLevel() + * \sa Logger::LogLevel + */ + Logger::LogLevel detailsLevel() const; + + //! Sets the current details level of appender. + /** + * \note This function is thread safe. + * + * \sa detalsLevel() + * \sa Logger::LogLevel + */ + void setDetailsLevel(Logger::LogLevel level); + + //! Sets the current details level of appender + /** + * This function is provided for convinience, it behaves like an above function. + * + * \sa detalsLevel() + * \sa Logger::LogLevel + */ + void setDetailsLevel(const QString& level); + + //! Tries to write the log record to this logger + /** + * This is the function called by Logger object to write a log message to the appender. + * + * \note This function is thread safe. + * + * \sa Logger::write() + * \sa detailsLevel() + */ + void write(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, const char* function, + const QString& message); + + protected: + //! Writes the log record to the logger instance + /** + * This function is called every time when user tries to write a message to this AbstractAppender instance using + * the write() function. Write function works as proxy and transfers only the messages with log level more or equal + * to the current logLevel(). + * + * Overload this function when you are implementing a custom appender. + * + * \note This function is not needed to be thread safe because it is never called directly by Logger object. The + * write() function works as a proxy and protects this function from concurrent access. + * + * \sa Logger::write() + */ + virtual void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, + const char* function, const QString& message) = 0; + + private: + QMutex m_writeMutex; + + Logger::LogLevel m_detailsLevel; + mutable QMutex m_detailsLevelMutex; +}; + +#endif // ABSTRACTAPPENDER_H diff --git a/rbutil/rbutilqt/logger/AbstractStringAppender.cpp b/rbutil/rbutilqt/logger/AbstractStringAppender.cpp new file mode 100644 index 0000000000..073ecb7782 --- /dev/null +++ b/rbutil/rbutilqt/logger/AbstractStringAppender.cpp @@ -0,0 +1,161 @@ +/* + Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License version 2.1 + as published by the Free Software Foundation and appearing in the file + LICENSE.LGPL included in the packaging of this file. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. +*/ +// Local +#include "AbstractStringAppender.h" + +// Qt +#include +#include +#include +#include + +const char formattingMarker = '%'; + +AbstractStringAppender::AbstractStringAppender() + : m_format(QLatin1String("%t{yyyy-MM-ddTHH:mm:ss.zzz} [%-7l] <%c> %m\n")) +{} + + +QString AbstractStringAppender::format() const +{ + QReadLocker locker(&m_formatLock); + return m_format; +} + + +void AbstractStringAppender::setFormat(const QString& format) +{ + QWriteLocker locker(&m_formatLock); + m_format = format; +} + + +QString AbstractStringAppender::stripFunctionName(const char* name) +{ + QRegExp rx("^.+\\s((?:[\\w\\d]+::)+)?([\\w\\d\\<\\>~]+)(?:\\(.*\\)).*$"); // XXX: SLOW! + return QString::fromLatin1(name).replace(rx, QString(QLatin1String("\\1\\2"))); +} + + +QString AbstractStringAppender::formattedString(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, + int line, const char* function, const QString& message) const +{ + QString f = format(); + const int size = f.size(); + + QString result; + + int i = 0; + while (i < f.size()) + { + QChar c = f.at(i); + + // We will silently ignore the broken % marker at the end of string + if (c != QLatin1Char(formattingMarker) || (i + 1) == size) + { + result.append(c); + } + else + { + QChar command = f.at(++i); + + // Check for the padding instruction + int fieldWidth = 0; + if (command.isDigit() || command.category() == QChar::Punctuation_Dash) + { + int j = 1; + while ((i + j) < size && f.at(i + j).isDigit()) + j++; + fieldWidth = f.mid(i, j).toInt(); + + i += j; + command = f.at(i); + } + + // Log record chunk to insert instead of formatting instruction + QString chunk; + + // Time stamp + if (command == QLatin1Char('t')) + { + if (f.at(i + 1) == QLatin1Char('{')) + { + int j = 1; + while ((i + 2 + j) < size && f.at(i + 2 + j) != QLatin1Char('}')) + j++; + + if ((i + 2 + j) < size) + { + chunk = timeStamp.toString(f.mid(i + 2, j)); + + i += j; + i += 2; + } + } + + if (chunk.isNull()) + chunk = timeStamp.toString(QLatin1String("HH:mm:ss.zzz")); + } + + // Log level + else if (command == QLatin1Char('l')) + chunk = Logger::levelToString(logLevel); + + // Uppercased log level + else if (command == QLatin1Char('L')) + chunk = Logger::levelToString(logLevel).toUpper(); + + // Filename + else if (command == QLatin1Char('F')) + chunk = QLatin1String(file); + + // Filename without a path + else if (command == QLatin1Char('f')) + chunk = QString(QLatin1String(file)).section('/', -1); + + // Source line number + else if (command == QLatin1Char('i')) + chunk = QString::number(line); + + // Function name, as returned by Q_FUNC_INFO + else if (command == QLatin1Char('C')) + chunk = QString::fromLatin1(function); + + // Stripped function name + else if (command == QLatin1Char('c')) + chunk = stripFunctionName(function); + + // Log message + else if (command == QLatin1Char('m')) + chunk = message; + + // We simply replace the double formatting marker (%) with one + else if (command == QLatin1Char(formattingMarker)) + chunk = QLatin1Char(formattingMarker); + + // Do not process any unknown commands + else + { + chunk = QLatin1Char(formattingMarker); + chunk.append(command); + } + + result.append(QString(QLatin1String("%1")).arg(chunk, fieldWidth)); + } + + ++i; + } + + return result; +} diff --git a/rbutil/rbutilqt/logger/AbstractStringAppender.h b/rbutil/rbutilqt/logger/AbstractStringAppender.h new file mode 100644 index 0000000000..3cef63bff9 --- /dev/null +++ b/rbutil/rbutilqt/logger/AbstractStringAppender.h @@ -0,0 +1,116 @@ +/* + Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License version 2.1 + as published by the Free Software Foundation and appearing in the file + LICENSE.LGPL included in the packaging of this file. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. +*/ +#ifndef ABSTRACTSTRINGAPPENDER_H +#define ABSTRACTSTRINGAPPENDER_H + +// Local +#include "CuteLogger_global.h" +#include + +// Qt +#include + + +//! The AbstractStringAppender class provides a convinient base for appenders working with plain text formatted logs. +/** + * AbstractSringAppender is the simple extension of the AbstractAppender class providing the convinient way to create + * custom log appenders working with a plain text formatted log targets. + * + * It have the formattedString() protected function that formats the logging arguments according to a format set with + * setFormat(). + * + * This class can not be directly instantiated because it contains pure virtual function inherited from AbstractAppender + * class. + * + * For more detailed description of customizing the log output format see the documentation on the setFormat() function. + */ +class CUTELOGGERSHARED_EXPORT AbstractStringAppender : public AbstractAppender +{ + public: + //! Constructs a new string appender object + AbstractStringAppender(); + + //! Returns the current log format string. + /** + * The default format is set to "%t{yyyy-MM-ddTHH:mm:ss.zzz} [%-7l] <%C> %m\n". You can set a different log record + * format using the setFormat() function. + * + * \sa setFormat(const QString&) + */ + QString format() const; + + //! Sets the logging format for writing strings to the log target with this appender. + /** + * The string format seems to be very common to those developers who have used a standart sprintf function. + * + * Log output format is a simple QString with the special markers (starting with % sign) which will be replaced with + * it's internal meaning when writing a log record. + * + * Controlling marker begins with the percent sign (%) which is followed by (optional) field width argument, the + * (necessary) single-letter command (which describes, what will be put to log record instead of marker, and an + * additional formatting argument (in the {} brackets) supported for some of the log commands. + * + * Field width argument works almost identically to the \c QString::arg() \c fieldWidth argument (and uses it + * internally). For example, \c "%-7l" will be replaced with the left padded debug level of the message + * (\c "Debug ") or something. For the more detailed description of it you may consider to look to the Qt + * Reference Documentation. + * + * Supported marker commands are: + * \arg \c %t - timestamp. You may specify your custom timestamp format using the {} brackets after the marker, + * timestamp format here will be similiar to those used in QDateTime::toString() function. For example, + * "%t{dd-MM-yyyy, HH:mm}" may be replaced with "17-12-2010, 20:17" depending on current date and time. + * The default format used here is "HH:mm:ss.zzz". + * \arg \c %l - Log level. Possible log levels are shown in the Logger::LogLevel enumerator. + * \arg \c %L - Uppercased log level. + * \arg \c %F - Full source file name (with path) of the file that requested log recording. Uses the \c __FILE__ + * preprocessor macro. + * \arg \c %f - Short file name (with stripped path). + * \arg \c %i - Line number in the source file. Uses the \c __LINE__ preprocessor macro. + * \arg \c %C - Name of function that called on of the LOG_* macros. Uses the \c Q_FUNC_INFO macro provided with + * Qt. + * \arg \c %c - [EXPERIMENTAL] Similiar to the %C, but the function name is stripped using stripFunctionName + * \arg \c %m - The log message sent by the caller. + * \arg \c %% - Convinient marker that is replaced with the single \c % mark. + * + * \note Format doesn't add \c '\\n' to the end of the format line. Please consider adding it manually. + * + * \sa format() + * \sa stripFunctionName() + * \sa Logger::LogLevel + */ + void setFormat(const QString&); + + //! Strips the long function signature (as added by Q_FUNC_INFO macro) + /** + * The string processing drops the returning type, arguments and template parameters of function. It is definitely + * useful for enchancing the log output readability. + * \return stripped function name + */ + static QString stripFunctionName(const char*); + + protected: + //! Returns the string to record to the logging target, formatted according to the format(). + /** + * \sa format() + * \sa setFormat(const QString&) + */ + QString formattedString(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, + const char* function, const QString& message) const; + + private: + QString m_format; + mutable QReadWriteLock m_formatLock; +}; + +#endif // ABSTRACTSTRINGAPPENDER_H diff --git a/rbutil/rbutilqt/logger/ConsoleAppender.cpp b/rbutil/rbutilqt/logger/ConsoleAppender.cpp new file mode 100644 index 0000000000..da4a43c740 --- /dev/null +++ b/rbutil/rbutilqt/logger/ConsoleAppender.cpp @@ -0,0 +1,25 @@ +/* + Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License version 2.1 + as published by the Free Software Foundation and appearing in the file + LICENSE.LGPL included in the packaging of this file. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. +*/ +// Local +#include "ConsoleAppender.h" + +// STL +#include + + +void ConsoleAppender::append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, + const char* function, const QString& message) +{ + std::cerr << qPrintable(formattedString(timeStamp, logLevel, file, line, function, message)); +} diff --git a/rbutil/rbutilqt/logger/ConsoleAppender.h b/rbutil/rbutilqt/logger/ConsoleAppender.h new file mode 100644 index 0000000000..fa685b5e82 --- /dev/null +++ b/rbutil/rbutilqt/logger/ConsoleAppender.h @@ -0,0 +1,32 @@ +/* + Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License version 2.1 + as published by the Free Software Foundation and appearing in the file + LICENSE.LGPL included in the packaging of this file. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. +*/ +#ifndef CONSOLEAPPENDER_H +#define CONSOLEAPPENDER_H + +#include "CuteLogger_global.h" +#include + +//! ConsoleAppender is the simple appender that writes the log records to the std::cerr output stream. +class CUTELOGGERSHARED_EXPORT ConsoleAppender : public AbstractStringAppender +{ + protected: + //! Writes the log record to the std::cerr stream. + /** + * \sa AbstractStringAppender::format() + */ + virtual void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, + const char* function, const QString& message); +}; + +#endif // CONSOLEAPPENDER_H diff --git a/rbutil/rbutilqt/logger/CuteLogger_global.h b/rbutil/rbutilqt/logger/CuteLogger_global.h new file mode 100644 index 0000000000..43e74affdb --- /dev/null +++ b/rbutil/rbutilqt/logger/CuteLogger_global.h @@ -0,0 +1,12 @@ +#ifndef CUTELOGGER_GLOBAL_H +#define CUTELOGGER_GLOBAL_H + +#include + +#if defined(CUTELOGGER_LIBRARY) +# define CUTELOGGERSHARED_EXPORT Q_DECL_EXPORT +#else +# define CUTELOGGERSHARED_EXPORT Q_DECL_IMPORT +#endif + +#endif // CUTELOGGER_GLOBAL_H diff --git a/rbutil/rbutilqt/logger/FileAppender.cpp b/rbutil/rbutilqt/logger/FileAppender.cpp new file mode 100644 index 0000000000..3e4d0e22f9 --- /dev/null +++ b/rbutil/rbutilqt/logger/FileAppender.cpp @@ -0,0 +1,85 @@ +/* + Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License version 2.1 + as published by the Free Software Foundation and appearing in the file + LICENSE.LGPL included in the packaging of this file. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. +*/ +// Local +#include "FileAppender.h" + +// STL +#include + + +FileAppender::FileAppender(const QString& fileName) +{ + setFileName(fileName); +} + + +FileAppender::~FileAppender() +{ + closeFile(); +} + + +QString FileAppender::fileName() const +{ + QMutexLocker locker(&m_logFileMutex); + return m_logFile.fileName(); +} + + +void FileAppender::setFileName(const QString& s) +{ + QMutexLocker locker(&m_logFileMutex); + if (m_logFile.isOpen()) + m_logFile.close(); + + m_logFile.setFileName(s); +} + + +bool FileAppender::openFile() +{ + bool isOpen = false; + if (!m_logFile.isOpen()) + { + if (m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) + { + m_logStream.setDevice(&m_logFile); + isOpen = true; + } + else + { + std::cerr << " Cannot open the log file " << qPrintable(m_logFile.fileName()) << std::endl; + } + } + return isOpen; +} + + +void FileAppender::append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, + const char* function, const QString& message) +{ + QMutexLocker locker(&m_logFileMutex); + + openFile(); + + m_logStream << formattedString(timeStamp, logLevel, file, line, function, message); + m_logStream.flush(); + m_logFile.flush(); +} + +void FileAppender::closeFile() +{ + QMutexLocker locker(&m_logFileMutex); + m_logFile.close(); +} diff --git a/rbutil/rbutilqt/logger/FileAppender.h b/rbutil/rbutilqt/logger/FileAppender.h new file mode 100644 index 0000000000..70a70c3e43 --- /dev/null +++ b/rbutil/rbutilqt/logger/FileAppender.h @@ -0,0 +1,63 @@ +/* + Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License version 2.1 + as published by the Free Software Foundation and appearing in the file + LICENSE.LGPL included in the packaging of this file. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. +*/ +#ifndef FILEAPPENDER_H +#define FILEAPPENDER_H + +// Logger +#include "CuteLogger_global.h" +#include + +// Qt +#include +#include + + +//! File is the simple appender that writes the log records to the plain text file. +class CUTELOGGERSHARED_EXPORT FileAppender : public AbstractStringAppender +{ + public: + //! Constructs the new file appender assigned to file with the given name. + FileAppender(const QString& fileName = QString()); + ~FileAppender(); + + //! Returns the name set by setFileName() or to the FileAppender constructor. + /** + * \sa setFileName() + */ + QString fileName() const; + + //! Sets the name of the file. The name can have no path, a relative path, or an absolute path. + /** + * \sa fileName() + */ + void setFileName(const QString&); + + protected: + //! Write the log record to the file. + /** + * \sa fileName() + * \sa AbstractStringAppender::format() + */ + virtual void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, + const char* function, const QString& message); + bool openFile(); + void closeFile(); + + private: + QFile m_logFile; + QTextStream m_logStream; + mutable QMutex m_logFileMutex; +}; + +#endif // FILEAPPENDER_H diff --git a/rbutil/rbutilqt/logger/LICENSE.LGPL b/rbutil/rbutilqt/logger/LICENSE.LGPL new file mode 100644 index 0000000000..5ab7695ab8 --- /dev/null +++ b/rbutil/rbutilqt/logger/LICENSE.LGPL @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/rbutil/rbutilqt/logger/Logger.cpp b/rbutil/rbutilqt/logger/Logger.cpp new file mode 100644 index 0000000000..33ba50ec58 --- /dev/null +++ b/rbutil/rbutilqt/logger/Logger.cpp @@ -0,0 +1,370 @@ +/* + Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License version 2.1 + as published by the Free Software Foundation and appearing in the file + LICENSE.LGPL included in the packaging of this file. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. +*/ +// Local +#include "Logger.h" +#include "AbstractAppender.h" + +// Qt +#include +#include +#include +#include +#include +#include + +// STL +#include + + +class LogDevice : public QIODevice +{ + public: + LogDevice() + : m_semaphore(1) + {} + + void lock(Logger::LogLevel logLevel, const char* file, int line, const char* function) + { + m_semaphore.acquire(); + + if (!isOpen()) + open(QIODevice::WriteOnly); + + m_logLevel = logLevel; + m_file = file; + m_line = line; + m_function = function; + } + + protected: + qint64 readData(char*, qint64) + { + return 0; + } + + qint64 writeData(const char* data, qint64 maxSize) + { + if (maxSize > 0) + Logger::write(m_logLevel, m_file, m_line, m_function, QString::fromLocal8Bit(QByteArray(data, maxSize))); + + m_semaphore.release(); + return maxSize; + } + + private: + QSemaphore m_semaphore; + Logger::LogLevel m_logLevel; + const char* m_file; + int m_line; + const char* m_function; +}; + + +// Forward declarations +static void cleanupLoggerPrivate(); + +#if QT_VERSION >= 0x050000 +static void qtLoggerMessageHandler(QtMsgType, const QMessageLogContext& context, const QString& msg); +#else +static void qtLoggerMessageHandler(QtMsgType type, const char* msg); +#endif + +/** + * \internal + * + * LoggerPrivate class implements the Singleton pattern in a thread-safe way. It uses a static pointer to itself + * protected by QReadWriteLock + * + * The appender list inside the LoggerPrivate class is also protected by QReadWriteLock so this class could be safely + * used in a multi-threaded application. + */ +class LoggerPrivate +{ + public: + static LoggerPrivate* m_self; + static QReadWriteLock m_selfLock; + + static LoggerPrivate* instance() + { + LoggerPrivate* result = 0; + { + QReadLocker locker(&m_selfLock); + result = m_self; + } + + if (!result) + { + QWriteLocker locker(&m_selfLock); + m_self = new LoggerPrivate; + +#if QT_VERSION >= 0x050000 + qInstallMessageHandler(qtLoggerMessageHandler); +#else + qInstallMsgHandler(qtLoggerMessageHandler); +#endif + qAddPostRoutine(cleanupLoggerPrivate); + result = m_self; + } + + return result; + } + + + LoggerPrivate() + : m_logDevice(0) + {} + + + ~LoggerPrivate() + { + // Cleanup appenders + QReadLocker appendersLocker(&m_appendersLock); + foreach (AbstractAppender* appender, m_appenders) + delete appender; + + // Cleanup device + QReadLocker deviceLocker(&m_logDeviceLock); + delete m_logDevice; + } + + + void registerAppender(AbstractAppender* appender) + { + QWriteLocker locker(&m_appendersLock); + + if (!m_appenders.contains(appender)) + m_appenders.append(appender); + else + std::cerr << "Trying to register appender that was already registered" << std::endl; + } + + + LogDevice* logDevice() + { + LogDevice* result = 0; + { + QReadLocker locker(&m_logDeviceLock); + result = m_logDevice; + } + + if (!result) + { + QWriteLocker locker(&m_logDeviceLock); + m_logDevice = new LogDevice; + result = m_logDevice; + } + + return result; + } + + + void write(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, const char* function, + const QString& message) + { + QReadLocker locker(&m_appendersLock); + + if (!m_appenders.isEmpty()) + { + foreach (AbstractAppender* appender, m_appenders) + appender->write(timeStamp, logLevel, file, line, function, message); + } + else + { + // Fallback + QString result = QString(QLatin1String("[%1] <%2> %3")).arg(Logger::levelToString(logLevel), -7) + .arg(function).arg(message); + + std::cerr << qPrintable(result) << std::endl; + } + + if (logLevel == Logger::Fatal) + abort(); + } + + + void write(Logger::LogLevel logLevel, const char* file, int line, const char* function, const QString& message) + { + write(QDateTime::currentDateTime(), logLevel, file, line, function, message); + } + + + void write(Logger::LogLevel logLevel, const char* file, int line, const char* function, const char* message) + { + write(logLevel, file, line, function, QString(message)); + } + + + QDebug write(Logger::LogLevel logLevel, const char* file, int line, const char* function) + { + LogDevice* d = logDevice(); + d->lock(logLevel, file, line, function); + return QDebug(d); + } + + + void writeAssert(const char* file, int line, const char* function, const char* condition) + { + write(Logger::Fatal, file, line, function, QString("ASSERT: \"%1\"").arg(condition)); + } + + private: + QList m_appenders; + QReadWriteLock m_appendersLock; + + LogDevice* m_logDevice; + QReadWriteLock m_logDeviceLock; +}; + +// Static fields initialization +LoggerPrivate* LoggerPrivate::m_self = 0; +QReadWriteLock LoggerPrivate::m_selfLock; + + +static void cleanupLoggerPrivate() +{ + QWriteLocker locker(&LoggerPrivate::m_selfLock); + + delete LoggerPrivate::m_self; + LoggerPrivate::m_self = 0; +} + + +#if QT_VERSION >= 0x050000 +static void qtLoggerMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) +{ + Logger::LogLevel level; + switch (type) + { + case QtDebugMsg: + level = Logger::Debug; + break; + case QtWarningMsg: + level = Logger::Warning; + break; + case QtCriticalMsg: + level = Logger::Error; + break; + case QtFatalMsg: + level = Logger::Fatal; + break; + } + + Logger::write(level, context.file, context.line, context.function, msg); +} + +#else + +static void qtLoggerMessageHandler(QtMsgType type, const char* msg) +{ + switch (type) + { + case QtDebugMsg: + LOG_DEBUG(msg); + break; + case QtWarningMsg: + LOG_WARNING(msg); + break; + case QtCriticalMsg: + LOG_ERROR(msg); + break; + case QtFatalMsg: + LOG_FATAL(msg); + break; + } +} +#endif + + +QString Logger::levelToString(Logger::LogLevel logLevel) +{ + switch (logLevel) + { + case Trace: + return QLatin1String("Trace"); + case Debug: + return QLatin1String("Debug"); + case Info: + return QLatin1String("Info"); + case Warning: + return QLatin1String("Warning"); + case Error: + return QLatin1String("Error"); + case Fatal: + return QLatin1String("Fatal"); + } + + return QString(); +} + + +Logger::LogLevel Logger::levelFromString(const QString& s) +{ + QString str = s.trimmed().toLower(); + + LogLevel result = Debug; + + if (str == QLatin1String("trace")) + result = Trace; + else if (str == QLatin1String("debug")) + result = Debug; + else if (str == QLatin1String("info")) + result = Info; + else if (str == QLatin1String("warning")) + result = Warning; + else if (str == QLatin1String("error")) + result = Error; + else if (str == QLatin1String("fatal")) + result = Fatal; + + return result; +} + + +void Logger::registerAppender(AbstractAppender* appender) +{ + LoggerPrivate::instance()->registerAppender(appender); +} + + +void Logger::write(const QDateTime& timeStamp, LogLevel logLevel, const char* file, int line, const char* function, + const QString& message) +{ + LoggerPrivate::instance()->write(timeStamp, logLevel, file, line, function, message); +} + + +void Logger::write(LogLevel logLevel, const char* file, int line, const char* function, const QString& message) +{ + LoggerPrivate::instance()->write(logLevel, file, line, function, message); +} + + +void Logger::write(LogLevel logLevel, const char* file, int line, const char* function, const char* message, ...) +{ + va_list va; + va_start(va, message); + LoggerPrivate::instance()->write(logLevel, file, line, function, QString().vsprintf(message,va)); + va_end(va); +} + +QDebug Logger::write(LogLevel logLevel, const char* file, int line, const char* function) +{ + return LoggerPrivate::instance()->write(logLevel, file, line, function); +} + + +void Logger::writeAssert(const char* file, int line, const char* function, const char* condition) +{ + LoggerPrivate::instance()->writeAssert(file, line, function, condition); +} diff --git a/rbutil/rbutilqt/logger/Logger.h b/rbutil/rbutilqt/logger/Logger.h new file mode 100644 index 0000000000..d056dfc25d --- /dev/null +++ b/rbutil/rbutilqt/logger/Logger.h @@ -0,0 +1,319 @@ +/* + Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License version 2.1 + as published by the Free Software Foundation and appearing in the file + LICENSE.LGPL included in the packaging of this file. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. +*/ +#ifndef LOGGER_H +#define LOGGER_H +/** + * \file Logger.h + * \brief A file containing the description of Logger class and and additional useful macros for logging + */ + +// Qt +#include +#include +class QDateTime; + +// Local +#include "CuteLogger_global.h" +class AbstractAppender; + + +//! Writes the trace log record +/** + * This macro is the convinient way to call Logger::write(). It uses the common preprocessor macros \c __FILE__, + * \c __LINE__ and the standart Qt \c Q_FUNC_INFO macros to automatically determine the needed parameters to call + * Logger::write(). + * + * \note This and other (LOG_INFO() etc...) macros uses the variadic macro arguments to give convinient usage form for + * the different versions of Logger::write() (using the QString or const char* argument or returning the QDebug class + * instance). Not all compilers will support this. Please, consider reviewing your compiler documentation to ensure + * it support __VA_ARGS__ macro. + * + * It is checked to work with GCC 4.4 or later. + * + * \sa Logger::LogLevel + * \sa Logger::write() + */ +#define LOG_TRACE(...) Logger::write(Logger::Trace, __FILE__, __LINE__, Q_FUNC_INFO, ##__VA_ARGS__) + +//! Writes the debug log record +/** + * This macro records the info log record using the Logger::write() function. It works identically to the LOG_TRACE() + * macro. + * + * \sa LOG_TRACE() + * \sa Logger::LogLevel + * \sa Logger::write() + */ +#define LOG_DEBUG(...) Logger::write(Logger::Debug, __FILE__, __LINE__, Q_FUNC_INFO, ##__VA_ARGS__) + +//! Write the info log record +/** + * This macro records the info log record using the Logger::write() function. It works identically to the LOG_TRACE() + * macro. + * + * \sa LOG_TRACE() + * \sa Logger::LogLevel + * \sa Logger::write() + */ +#define LOG_INFO(...) Logger::write(Logger::Info, __FILE__, __LINE__, Q_FUNC_INFO, ##__VA_ARGS__) + +//! Write the warning log record +/** + * This macro records the warning log record using the Logger::write() function. It works identically to the LOG_TRACE() + * macro. + * + * \sa LOG_TRACE() + * \sa Logger::LogLevel + * \sa Logger::write() + */ +#define LOG_WARNING(...) Logger::write(Logger::Warning, __FILE__, __LINE__, Q_FUNC_INFO, ##__VA_ARGS__) + +//! Write the error log record +/** + * This macro records the error log record using the Logger::write() function. It works identically to the LOG_TRACE() + * macro. + * + * \sa LOG_TRACE() + * \sa Logger::LogLevel + * \sa Logger::write() + */ +#define LOG_ERROR(...) Logger::write(Logger::Error, __FILE__, __LINE__, Q_FUNC_INFO, ##__VA_ARGS__) + +//! Write the fatal log record +/** + * This macro records the fatal log record using the Logger::write() function. It works identically to the LOG_TRACE() + * macro. + * + * \note Recording of the log record using the Logger::Fatal log level will lead to calling the STL abort() + * function, which will interrupt the running of your software and begin the writing of the core dump. + * + * \sa LOG_TRACE() + * \sa Logger::LogLevel + * \sa Logger::write() + */ +#define LOG_FATAL(...) Logger::write(Logger::Fatal, __FILE__, __LINE__, Q_FUNC_INFO, ##__VA_ARGS__) + +//! Check the assertion +/** + * This macro is a convinient and recommended to use way to call Logger::writeAssert() function. It uses the + * preprocessor macros (as the LOG_DEBUG() does) to fill the necessary arguments of the Logger::writeAssert() call. It + * also uses undocumented but rather mature and stable \c qt_noop() function (which does nothing) when the assertion + * is true. + * + * Example: + * \code + * bool b = checkSomething(); + * ... + * LOG_ASSERT(b == true); + * \endcode + * + * \sa Logger::writeAssert() + */ +#define LOG_ASSERT(cond) ((!(cond)) ? Logger::writeAssert(__FILE__, __LINE__, Q_FUNC_INFO, #cond) : qt_noop()) + + +/** + * \mainpage + * + * Logger is a simple way to write the history of your application lifecycle to any target logging device (which is + * called Appender and may write to any target you will implement with it: console, text file, XML or something - you + * choose) and to map logging message to a class, function, source file and line of code which it is called from. + * + * Some simple appenders (which may be considered an examples) are provided with the logger itself: see ConsoleAppender + * and FileAppender documentation. + * + * It supports using it in a multithreaded applications, so ALL of its functions are thread safe. + * + * Simple usage example: + * \code + * #include + * + * #include + * #include + * + * int main(int argc, char* argv[]) + * { + * QCoreApplication app(argc, argv); + * ... + * ConsoleAppender* consoleAppender = new ConsoleAppender(); + * consoleAppender->setFormat("[%-7l] <%C> %m\n"); + * Logger::registerAppender(consoleAppender); + * ... + * LOG_INFO("Starting the application"); + * int result = app.exec(); + * ... + * if (result) + * LOG_WARNING() << "Something went wrong." << "Result code is" << result; + * + * return result; + * } + * \endcode + * + * Logger internally uses the lazy-initialized singleton object and needs no definite initialization, but you may + * consider registering a log appender before calling any log recording functions or macros. + * + * The library design of Logger allows you to simply mass-replace all occurrences of qDebug and similiar calls with + * similiar Logger macros (e.g. LOG_DEBUG) + * + * \note Logger uses a singleton class which must live through all the application life cycle and cleans it on the + * destruction of the QCoreApplication (or QApplication) instance. It needs a QCoreApplication instance to be + * created before any of the Logger's functions are called. + * + * \sa AbstractAppender + * \sa LOG_TRACE, LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_FATAL + * \sa LOG_ASSERT + */ + +//! Very simple but rather powerful component which may be used for logging your application activities. +class CUTELOGGERSHARED_EXPORT Logger +{ + public: + //! Describes the possible severity levels of the log records + enum LogLevel + { + Trace, //!< Trace level. Can be used for mostly unneeded records used for internal code tracing. + Debug, //!< Debug level. Useful for non-necessary records used for the debugging of the software. + Info, //!< Info level. Can be used for informational records, which may be interesting for not only developers. + Warning, //!< Warning. May be used to log some non-fatal warnings detected by your application. + Error, //!< Error. May be used for a big problems making your application work wrong but not crashing. + Fatal //!< Fatal. Used for unrecoverable errors, crashes the application right after the log record is written. + }; + + //! Converts the LogLevel enum value to its string representation + /** + * \param logLevel Log level to convert + * + * \sa LogLevel + * \sa levelFromString() + */ + static QString levelToString(LogLevel logLevel); + + //! Converts the LogLevel string representation to enum value + /** + * Comparation of the strings is case independent. If the log level string provided cannot be understood + * Logger::Debug is returned. + * + * \param s String to be decoded + * + * \sa LogLevel + * \sa levelToString() + */ + static LogLevel levelFromString(const QString& s); + + //! Registers the appender to write the log records to + /** + * On the log writing call (using one of the macros or the write() function) Logger traverses through the list of + * the appenders and writes a log records to the each of them. Please, look through the AbstractAppender + * documentation to understand the concept of appenders. + * + * If no appenders was added to Logger, it falls back to logging into the \c std::cerr STL stream. + * + * \param appender Appender to register in the Logger + * + * \note Logger takes ownership on the appender and it will delete it on the application exit. According to this, + * appenders must be created on heap to prevent double destruction of the appender. + * + * \sa AbstractAppender + */ + static void registerAppender(AbstractAppender* appender); + + //! Writes the log record + /** + * Writes the log records with the supplied arguments to all the registered appenders. + * + * \note It is not recommended to call this function directly. Instead of this you can just call one of the macros + * (LOG_TRACE, LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_FATAL) that will supply all the needed + * information to this function. + * + * \param timeStamp - the time stamp of the record + * \param logLevel - the log level of the record + * \param file - the name of the source file that requested the log record + * \param line - the line of the code of source file that requested the log record + * \param function - name of the function that requested the log record + * \param message - log message + * + * \note Recording of the log record using the Logger::Fatal log level will lead to calling the STL abort() + * function, which will interrupt the running of your software and begin the writing of the core dump. + * + * \sa LogLevel + * \sa LOG_TRACE, LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_FATAL + * \sa AbstractAppender + */ + static void write(const QDateTime& timeStamp, LogLevel logLevel, const char* file, int line, const char* function, + const QString& message); + + /** + * This is the overloaded function provided for the convinience. It behaves identically to the above function. + * + * This function uses the current timestamp obtained with \c QDateTime::currentDateTime(). + * + * \sa write() + */ + static void write(LogLevel logLevel, const char* file, int line, const char* function, const QString& message); + + /** + * This is the overloaded function provided for the convinience. It behaves identically to the above function. + * + * This function uses the current timestamp obtained with \c QDateTime::currentDateTime(). Also it supports writing + * const char* instead of \c QString and converts it internally using the \c QString::fromAscii(). If you + * want this function to support the non-ascii strings, you will need to setup the codec using the + * \c QTextCodec::setCodecForCStrings() + * + * \sa write() + */ + static void write(LogLevel logLevel, const char* file, int line, const char* function, const char* message, ...); + + /** + * This is the overloaded function provided for the convinience. It behaves identically to the above function. + * + * This function doesn't accept any log message as argument. It returns the \c QDebug object that can be written + * using the stream functions. For example, you may like to write: + * \code + * LOG_DEBUG() << "This is the size" << size << "of the element" << elementName; + * \endcode + * instead of writing + * \code + * LOG_DEBUG(QString(QLatin1String("This is the size %1x%2 of the element %3")) + * .arg(size.x()).arg(size.y()).arg(elementName)); + * \endcode + * + * Please consider reading the Qt Reference Documentation for the description of the QDebug class usage syntax. + * + * \note This overload is definitely more pleasant to use than the first write() overload, but it behaves definitely + * slower than all the above overloads. + * + * \sa write() + */ + static QDebug write(LogLevel logLevel, const char* file, int line, const char* function); + + //! Writes the assertion + /** + * This function writes the assertion record using the write() function. + * + * The assertion record is always written using the Logger::Fatal log level which leads to the abortation of the + * program and generation of the core dump (if supported). + * + * The message written to the appenders will be identical to the \c condition argument prefixed with the + * ASSERT: notification. + * + * \note It is not recommended to call this function directly. Instead of this you can just call the LOG_ASSERT + * macro that will supply all the needed information to this function. + * + * \sa LOG_ASSERT + * \sa write() + */ + static void writeAssert(const char* file, int line, const char* function, const char* condition); +}; + +#endif // LOGGER_H diff --git a/rbutil/rbutilqt/logger/OutputDebugAppender.cpp b/rbutil/rbutilqt/logger/OutputDebugAppender.cpp new file mode 100644 index 0000000000..2d7facbd98 --- /dev/null +++ b/rbutil/rbutilqt/logger/OutputDebugAppender.cpp @@ -0,0 +1,31 @@ +/* + Copyright (c) 2010 Karl-Heinz Reichel (khreichel at googlemail dot com) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License version 2.1 + as published by the Free Software Foundation and appearing in the file + LICENSE.LGPL included in the packaging of this file. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. +*/ +// Local +#include "OutputDebugAppender.h" + +// STL +#include + + +void OutputDebugAppender::append(const QDateTime& timeStamp, + Logger::LogLevel logLevel, + const char* file, + int line, + const char* function, + const QString& message) +{ + QString s = formattedString(timeStamp, logLevel, file, line, function, message); + OutputDebugStringW((LPCWSTR) s.utf16()); +} + diff --git a/rbutil/rbutilqt/logger/OutputDebugAppender.h b/rbutil/rbutilqt/logger/OutputDebugAppender.h new file mode 100644 index 0000000000..f5a5b8c588 --- /dev/null +++ b/rbutil/rbutilqt/logger/OutputDebugAppender.h @@ -0,0 +1,33 @@ +/* + Copyright (c) 2010 Karl-Heinz Reichel (khreichel at googlemail dot com) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License version 2.1 + as published by the Free Software Foundation and appearing in the file + LICENSE.LGPL included in the packaging of this file. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. +*/ + +#ifndef OUTPUTDEBUGAPPENDER_H +#define OUTPUTDEBUGAPPENDER_H + +#include "CuteLogger_global.h" +#include + +//! OutputDebugAppender is the appender that writes the log records to the Microsoft Debug Log +class CUTELOGGERSHARED_EXPORT OutputDebugAppender : public AbstractStringAppender +{ + protected: + //! Writes the log record to the windows debug log. + /** + * \sa AbstractStringAppender::format() + */ + virtual void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, + const char* function, const QString& message); +}; + +#endif // OUTPUTDEBUGAPPENDER_H diff --git a/rbutil/rbutilqt/logger/README.ROCKBOX b/rbutil/rbutilqt/logger/README.ROCKBOX new file mode 100644 index 0000000000..08f537fb3f --- /dev/null +++ b/rbutil/rbutilqt/logger/README.ROCKBOX @@ -0,0 +1,7 @@ +This folder contains the cutelogger project for logging functionality. +These files are distributed under the LGPL v2 or later. +The source files have been last synced with the projects at +https://gitorious.org/cutelogger to commit +e3c2745c6c5f38896f87472e01ea2caf2d9e211b. + + diff --git a/rbutil/rbutilqt/main.cpp b/rbutil/rbutilqt/main.cpp index 7d57f42290..9f272281d4 100644 --- a/rbutil/rbutilqt/main.cpp +++ b/rbutil/rbutilqt/main.cpp @@ -21,6 +21,9 @@ #include #include "rbutilqt.h" #include "systrace.h" +#include "Logger.h" +#include "ConsoleAppender.h" +#include "FileAppender.h" #ifdef STATIC #include @@ -28,14 +31,19 @@ Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif - int main( int argc, char ** argv ) { -#if QT_VERSION < 0x050000 - qInstallMsgHandler(SysTrace::debug); -#else - qInstallMessageHandler(SysTrace::debug); -#endif QApplication app( argc, argv ); + ConsoleAppender* consoleAppender = new ConsoleAppender(); + consoleAppender->setFormat("[%f:%i %L] %m\n"); + Logger::registerAppender(consoleAppender); + SysTrace::rotateTrace(); + QString tracefile = QDir::tempPath() + "/rbutil-trace.log"; + FileAppender* fileAppender = new FileAppender(); + fileAppender->setFormat("[%f:%i %L] %m\n"); + fileAppender->setFileName(tracefile); + Logger::registerAppender(fileAppender); + LOG_INFO() << "Starting trace at" << QDateTime::currentDateTime().toString(Qt::ISODate); + #if defined(Q_OS_MAC) QDir dir(QApplication::applicationDirPath()); dir.cdUp(); diff --git a/rbutil/rbutilqt/progressloggergui.cpp b/rbutil/rbutilqt/progressloggergui.cpp index 1f5b2c0cd3..41df0600f0 100644 --- a/rbutil/rbutilqt/progressloggergui.cpp +++ b/rbutil/rbutilqt/progressloggergui.cpp @@ -142,9 +142,9 @@ void ProgressLoggerGui::show() void ProgressLoggerGui::saveErrorLog() { - QString filename = QFileDialog::getSaveFileName(downloadProgress, tr("Save system trace log"), - QDir::homePath(), "*.log"); - if(filename == "") + QString filename = QFileDialog::getSaveFileName(downloadProgress, + tr("Save system trace log"), QDir::homePath(), "*.log"); + if(filename.isEmpty()) return; QFile file(filename); @@ -155,6 +155,7 @@ void ProgressLoggerGui::saveErrorLog() QString loggerTexts = "\n*********************************************\n" "*************** Logger *******************\n" "*********************************************\n"; + file.write(loggerTexts.toUtf8(), loggerTexts.size()); diff --git a/rbutil/rbutilqt/rbutilqt.cpp b/rbutil/rbutilqt/rbutilqt.cpp index f83020050a..e7c2eaaf28 100644 --- a/rbutil/rbutilqt/rbutilqt.cpp +++ b/rbutil/rbutilqt/rbutilqt.cpp @@ -49,6 +49,8 @@ #include "bootloaderinstallbase.h" #include "bootloaderinstallhelper.h" +#include "Logger.h" + #if defined(Q_OS_LINUX) #include #endif @@ -66,10 +68,10 @@ QList RbUtilQt::translators; RbUtilQt::RbUtilQt(QWidget *parent) : QMainWindow(parent) { // startup log - qDebug() << "======================================"; - qDebug() << "[System] Rockbox Utility " VERSION; - qDebug() << "[System] Qt version:" << qVersion(); - qDebug() << "======================================"; + LOG_INFO() << "======================================"; + LOG_INFO() << "Rockbox Utility" << VERSION; + LOG_INFO() << "Qt version:" << qVersion(); + LOG_INFO() << "======================================"; absolutePath = qApp->applicationDirPath(); @@ -110,7 +112,7 @@ RbUtilQt::RbUtilQt(QWidget *parent) : QMainWindow(parent) "Please don't do this, running under Wine will fail. " "Use the native Linux binary instead."), QMessageBox::Ok, QMessageBox::Ok); - qDebug() << "[RbUtil] WINE DETECTED!"; + LOG_WARNING() << "WINE DETECTED!"; RegCloseKey(hk); } #endif @@ -181,15 +183,6 @@ RbUtilQt::RbUtilQt(QWidget *parent) : QMainWindow(parent) void RbUtilQt::shutdown(void) { - // restore default message handler to prevent trace accesses during - // object destruction -- the trace object could already be destroyed. - // Fixes segfaults on exit. -#if QT_VERSION < 0x050000 - qInstallMsgHandler(0); -#else - qInstallMessageHandler(0); -#endif - SysTrace::save(); this->close(); } @@ -229,7 +222,7 @@ void RbUtilQt::downloadInfo() connect(qApp, SIGNAL(lastWindowClosed()), daily, SLOT(abort())); daily->setCache(false); ui.statusbar->showMessage(tr("Downloading build information, please wait ...")); - qDebug() << "[RbUtil] downloading build info"; + LOG_INFO() << "downloading build info"; daily->setFile(&buildInfo); daily->getFile(QUrl(SystemInfo::value(SystemInfo::BuildInfoUrl).toString())); } @@ -238,7 +231,7 @@ void RbUtilQt::downloadInfo() void RbUtilQt::downloadDone(bool error) { if(error) { - qDebug() << "[RbUtil] network error:" << daily->errorString(); + LOG_INFO() << "network error:" << daily->errorString(); ui.statusbar->showMessage(tr("Can't get version information!")); QMessageBox::critical(this, tr("Network error"), tr("Can't get version information.\n" @@ -246,7 +239,7 @@ void RbUtilQt::downloadDone(bool error) .arg(daily->errorString())); return; } - qDebug() << "[RbUtil] network status:" << daily->errorString(); + LOG_INFO() << "network status:" << daily->errorString(); // read info into ServerInfo object buildInfo.open(); @@ -320,7 +313,7 @@ void RbUtilQt::configDialog() void RbUtilQt::updateSettings() { - qDebug() << "[RbUtil] updating current settings"; + LOG_INFO() << "updating current settings"; updateDevice(); manual->updateManual(); QString c = RbSettings::value(RbSettings::CachePath).toString(); @@ -409,7 +402,7 @@ void RbUtilQt::backup(void) void RbUtilQt::installdone(bool error) { - qDebug() << "[RbUtil] install done"; + LOG_INFO() << "install done"; m_installed = true; m_error = error; } @@ -464,7 +457,7 @@ void RbUtilQt::installVoice() voiceurl.replace("%MODEL%", model); voiceurl.replace("%RELVERSION%", relversion); - qDebug() << "[RbUtil] voicefile URL:" << voiceurl; + LOG_INFO() << "voicefile URL:" << voiceurl; // create logger logger = new ProgressLoggerGui(this); @@ -633,7 +626,7 @@ QUrl RbUtilQt::proxy() else if(proxytype == "system") proxy = System::systemProxy(); - qDebug() << "[RbUtilQt] Proxy is" << proxy; + LOG_INFO() << "Proxy is" << proxy; return proxy; } @@ -675,7 +668,7 @@ void RbUtilQt::checkUpdate(void) void RbUtilQt::downloadUpdateDone(bool error) { if(error) { - qDebug() << "[RbUtil] network error:" << update->errorString(); + LOG_INFO() << "network error:" << update->errorString(); } else { QString toParse(update->readAll()); @@ -688,7 +681,7 @@ void RbUtilQt::downloadUpdateDone(bool error) rbutilList << searchString.cap(1); pos += searchString.matchedLength(); } - qDebug() << "[RbUtilQt] Checking for update"; + LOG_INFO() << "Checking for update"; QString newVersion = ""; QString foundVersion = ""; diff --git a/rbutil/rbutilqt/rbutilqt.pri b/rbutil/rbutilqt/rbutilqt.pri index b8193d56ab..d67bf65bc3 100644 --- a/rbutil/rbutilqt/rbutilqt.pri +++ b/rbutil/rbutilqt/rbutilqt.pri @@ -87,6 +87,11 @@ SOURCES += \ mspack/system-mspack.c \ base/mspackutil.cpp \ base/archiveutil.cpp \ + logger/AbstractAppender.cpp \ + logger/AbstractStringAppender.cpp \ + logger/ConsoleAppender.cpp \ + logger/FileAppender.cpp \ + logger/Logger.cpp \ HEADERS += \ diff --git a/rbutil/rbutilqt/rbutilqt.pro b/rbutil/rbutilqt/rbutilqt.pro index 6a40de6422..4a4016c21d 100644 --- a/rbutil/rbutilqt/rbutilqt.pro +++ b/rbutil/rbutilqt/rbutilqt.pro @@ -110,6 +110,7 @@ INCLUDEPATH = $$_PRO_FILE_PWD_ $$_PRO_FILE_PWD_/irivertools \ $$_PRO_FILE_PWD_/zlib $$_PRO_FILE_PWD_/gui INCLUDEPATH += $$RBBASE_DIR/rbutil/ipodpatcher $$RBBASE_DIR/rbutil/sansapatcher \ $$RBBASE_DIR/tools/rbspeex $$RBBASE_DIR/tools +INCLUDEPATH += logger DEPENDPATH = $$INCLUDEPATH @@ -143,13 +144,11 @@ contains(QT_MAJOR_VERSION, 5) { dbg { CONFIG += debug thread qt warn_on - DEFINES -= QT_NO_DEBUG_OUTPUT DEFINES += DBG message("debug") } !dbg { CONFIG += release thread qt - DEFINES -= QT_NO_DEBUG_OUTPUT DEFINES += NODEBUG message("release") } diff --git a/rbutil/rbutilqt/systrace.cpp b/rbutil/rbutilqt/systrace.cpp index dc8534af03..5e42e1b2d8 100644 --- a/rbutil/rbutilqt/systrace.cpp +++ b/rbutil/rbutilqt/systrace.cpp @@ -22,10 +22,8 @@ #include "ui_systracefrm.h" #include "rbsettings.h" +#include "Logger.h" -QString SysTrace::debugbuffer; -QString SysTrace::lastmessage; -unsigned int SysTrace::repeat = 0; SysTrace::SysTrace(QWidget *parent) : QDialog(parent) { @@ -43,7 +41,28 @@ SysTrace::SysTrace(QWidget *parent) : QDialog(parent) void SysTrace::refresh(void) { int pos = ui.textTrace->verticalScrollBar()->value(); - flush(); + + QString debugbuffer; + QFile tracefile(QDir::tempPath() + "/rbutil-trace.log"); + tracefile.open(QIODevice::ReadOnly); + QTextStream c(&tracefile); + QString line; + QString color; + while(!c.atEnd()) { + line = c.readLine(); + if(line.contains("WARNING")) + color = "orange"; + else if(line.contains("ERROR")) + color = "red"; +#if 0 + else if(line.contains("INFO")) + color = "green"; +#endif + else + color = "black"; + debugbuffer += QString("
    %2
    ").arg(color, line); + } + tracefile.close(); ui.textTrace->setHtml("
    " + debugbuffer + "
    "); ui.textTrace->verticalScrollBar()->setValue(pos); QString oldlog = RbSettings::value(RbSettings::CachePath).toString() @@ -52,23 +71,26 @@ void SysTrace::refresh(void) } +QString SysTrace::getTrace(void) +{ + QString debugbuffer; + QFile tracefile(QDir::tempPath() + "/rbutil-trace.log"); + tracefile.open(QIODevice::ReadOnly); + QTextStream c(&tracefile); + debugbuffer = c.readAll(); + tracefile.close(); + + return debugbuffer; +} + + void SysTrace::save(QString filename) { if(filename.isEmpty()) - filename = RbSettings::value(RbSettings::CachePath).toString() - + "/rbutil-trace.log"; - // make sure any repeat detection is flushed - flush(); - // append save date to the trace. Append it directly instead of using - // qDebug() as the handler might have been unregistered. - debugbuffer.append("[SysTrace] saving trace at "); - debugbuffer.append(QDateTime::currentDateTime().toString(Qt::ISODate)); - debugbuffer.append("\n"); - QFile fh(filename); - if(!fh.open(QIODevice::WriteOnly)) return; - fh.write(debugbuffer.toUtf8(), debugbuffer.size()); - fh.close(); + LOG_INFO() << "saving trace at" << QDateTime::currentDateTime().toString(Qt::ISODate); + QFile::copy(QDir::tempPath() + "/rbutil-trace.log", filename); + } void SysTrace::saveCurrentTrace(void) @@ -87,59 +109,19 @@ void SysTrace::savePreviousTrace(void) if(fp.isEmpty()) return; - QString oldlog = RbSettings::value(RbSettings::CachePath).toString() - + "/rbutil-trace.log"; + QString oldlog = QDir::tempPath() + "/rbutil-trace.log.1"; QFile::copy(oldlog, fp); return; } -#if QT_VERSION < 0x050000 -void SysTrace::debug(QtMsgType type, const char* msg) -{ - (void)type; - if(lastmessage != msg) { - lastmessage = msg; - flush(); - debugbuffer.append(QString::fromLocal8Bit(msg) + "\n"); -#if !defined(NODEBUG) - fprintf(stderr, "%s\n", msg); -#endif - repeat = 1; - } - else { - repeat++; - } -} -#else -void SysTrace::debug(QtMsgType type, const QMessageLogContext &context, const QString &msg) -{ - (void)type; - (void)context; - QByteArray localMsg = msg.toLocal8Bit(); - if(lastmessage != msg) { - lastmessage = msg; - flush(); - debugbuffer.append(msg + "\n"); -#if !defined(NODEBUG) - fprintf(stderr, "%s\n", localMsg.constData()); -#endif - repeat = 1; - } - else { - repeat++; - } -} -#endif -void SysTrace::flush(void) +void SysTrace::rotateTrace(void) { - if(repeat > 1) { - debugbuffer.append( - QString(" (Last message repeated %1 times.)\n").arg(repeat)); -#if !defined(NODEBUG) - fprintf(stderr, " (Last message repeated %i times.)\n", repeat); -#endif + QString f = QDir::tempPath() + "/rbutil-trace.log.1"; + if(QFileInfo(f).exists()) { + QFile::remove(f); } + QFile::rename(QDir::tempPath() + "/rbutil-trace.log", f); } diff --git a/rbutil/rbutilqt/systrace.h b/rbutil/rbutilqt/systrace.h index 092d115489..b0a6f70fa6 100644 --- a/rbutil/rbutilqt/systrace.h +++ b/rbutil/rbutilqt/systrace.h @@ -29,20 +29,12 @@ class SysTrace : public QDialog Q_OBJECT public: SysTrace(QWidget *parent); -#if QT_VERSION < 0x050000 - static void debug(QtMsgType type, const char* msg); -#else - static void debug(QtMsgType type, const QMessageLogContext &context, const QString &msg); -#endif - static QString getTrace() {return debugbuffer;} + static QString getTrace(void); static void save(QString filename = ""); + static void rotateTrace(void); private: - static void flush(void); void changeEvent(QEvent *event); Ui::SysTraceFrm ui; - static QString debugbuffer; - static QString lastmessage; - static unsigned int repeat; private slots: void saveCurrentTrace(void); diff --git a/rbutil/rbutilqt/themesinstallwindow.cpp b/rbutil/rbutilqt/themesinstallwindow.cpp index 2003b41c02..c514c65b0c 100644 --- a/rbutil/rbutilqt/themesinstallwindow.cpp +++ b/rbutil/rbutilqt/themesinstallwindow.cpp @@ -28,6 +28,7 @@ #include "systeminfo.h" #include "rockboxinfo.h" #include "version.h" +#include "Logger.h" ThemesInstallWindow::ThemesInstallWindow(QWidget *parent) : QDialog(parent) { @@ -79,7 +80,7 @@ void ThemesInstallWindow::downloadInfo() = RockboxInfo(RbSettings::value(RbSettings::Mountpoint).toString()); themesInfo.open(); - qDebug() << "[Themes] downloading info to" << themesInfo.fileName(); + LOG_INFO() << "downloading info to" << themesInfo.fileName(); themesInfo.close(); QString infoUrl = SystemInfo::value(SystemInfo::ThemesInfoUrl).toString(); @@ -89,7 +90,7 @@ void ThemesInstallWindow::downloadInfo() infoUrl.replace("%RELEASE%", installInfo.release()); infoUrl.replace("%RBUTILVER%", VERSION); QUrl url = QUrl(infoUrl); - qDebug() << "[Themes] Info URL:" << url; + LOG_INFO() << "Info URL:" << url; getter->setFile(&themesInfo); connect(getter, SIGNAL(done(bool)), this, SLOT(downloadDone(bool))); @@ -101,13 +102,13 @@ void ThemesInstallWindow::downloadInfo() void ThemesInstallWindow::downloadDone(int id, bool error) { downloadDone(error); - qDebug() << "[Themes] Download" << id << "done, error:" << error; + LOG_INFO() << "Download" << id << "done, error:" << error; } void ThemesInstallWindow::downloadDone(bool error) { - qDebug() << "[Themes] Download done, error:" << error; + LOG_INFO() << "Download done, error:" << error; disconnect(logger, SIGNAL(aborted()), getter, SLOT(abort())); disconnect(logger, SIGNAL(aborted()), this, SLOT(close())); @@ -115,10 +116,10 @@ void ThemesInstallWindow::downloadDone(bool error) QSettings iniDetails(themesInfo.fileName(), QSettings::IniFormat, this); QStringList tl = iniDetails.childGroups(); - qDebug() << "[Themes] Theme site result:" - << iniDetails.value("error/code").toString() - << iniDetails.value("error/description").toString() - << iniDetails.value("error/query").toString(); + LOG_INFO() << "Theme site result:" + << iniDetails.value("error/code").toString() + << iniDetails.value("error/description").toString() + << iniDetails.value("error/query").toString(); if(error) { logger->addItem(tr("Network error: %1.\n" @@ -132,8 +133,8 @@ void ThemesInstallWindow::downloadDone(bool error) } // handle possible error codes if(iniDetails.value("error/code").toInt() != 0 || !iniDetails.contains("error/code")) { - qDebug() << "[Themes] Theme site returned an error:" - << iniDetails.value("error/code"); + LOG_ERROR() << "Theme site returned an error:" + << iniDetails.value("error/code"); logger->addItem(tr("the following error occured:\n%1") .arg(iniDetails.value("error/description", "unknown error").toString()), LOGERROR); logger->setFinished(); @@ -152,7 +153,7 @@ void ThemesInstallWindow::downloadDone(bool error) iniDetails.endGroup(); continue; } - qDebug() << "[Themes] adding to list:" << tl.at(i); + LOG_INFO() << "adding to list:" << tl.at(i); // convert to unicode and replace HTML-specific entities QByteArray raw = iniDetails.value("name").toByteArray(); QTextCodec* codec = QTextCodec::codecForHtml(raw); @@ -175,7 +176,7 @@ void ThemesInstallWindow::downloadDone(bool error) msg = iniDetails.value("status/msg." + lang).toString(); else msg = iniDetails.value("status/msg").toString(); - qDebug() << "[Themes] MOTD" << msg; + LOG_INFO() << "MOTD" << msg; if(!msg.isEmpty()) QMessageBox::information(this, tr("Information"), msg); } @@ -240,7 +241,7 @@ void ThemesInstallWindow::updateDetails(QListWidgetItem* cur, QListWidgetItem* p void ThemesInstallWindow::updateImage(bool error) { - qDebug() << "[Themes] Updating image:"<< !error; + LOG_INFO() << "Updating image:"<< !error; if(error) { ui.themePreview->clear(); @@ -266,8 +267,7 @@ void ThemesInstallWindow::updateImage(bool error) void ThemesInstallWindow::resizeEvent(QResizeEvent* e) { - qDebug() << "[Themes]" << e; - + (void)e; QPixmap p, q; QSize img; img.setHeight(ui.themePreview->height()); @@ -344,13 +344,13 @@ void ThemesInstallWindow::install() QDate().currentDate().toString("yyyyMMdd")).toString()); iniDetails.endGroup(); } - qDebug() << "[Themes] installing:" << themes; + LOG_INFO() << "installing:" << themes; if(logger == NULL) logger = new ProgressLoggerGui(this); logger->show(); QString mountPoint = RbSettings::value(RbSettings::Mountpoint).toString(); - qDebug() << "[Themes] mountpoint:" << mountPoint; + LOG_INFO() << "mountpoint:" << mountPoint; // show dialog with error if mount point is wrong if(!QFileInfo(mountPoint).isDir()) { logger->addItem(tr("Mount point is wrong!"),LOGERROR);