未验证 提交 c4a051a9 编写于 作者: 梦醒贰零壹柒's avatar 梦醒贰零壹柒 提交者: GitHub

Merge pull request #20 from mengxing2017/17-config-log

17 config log
...@@ -10,7 +10,6 @@ bin/rms ...@@ -10,7 +10,6 @@ bin/rms
*~ *~
*.swp *.swp
build/* build/*
compile/*
.qmake.stash .qmake.stash
moc_* moc_*
Makefile Makefile
......
# FoodBevManage # RMS
这个是餐饮管理系统
本程序跨平台,支持linux和win完美运行 RMS是 RestaurantManagementSystem(餐厅管理系统)缩写
添加程序目录结构
```html
├── copyleft
├── data.db
├── dist
├── doc
├── FoodBevManage.pro
├── FoodBevManage.pro.user
├── lib
├── README.md
├── res
│   ├── images
│   │   ├── Add.png
│   │   ├── addUser.png
│   │   ├── Login.png
│   │   ├── Quit.png
│   │   ├── Reckoning.png
│   │   ├── Start.png
│   │   └── Stat.png
│   └── ui
│   ├── add_reduce_dialog.ui
│   ├── check_outdialog.ui
│   ├── dayincomequery_dialog.ui
│   ├── dishescountdialog.ui
│   ├── foodinfo_dialog.ui
│   ├── logindialog.ui
│   ├── mainwindow.ui
│   ├── monthincomequery_dialog.ui
│   ├── orderdishesdialog.ui
│   ├── selectseatdialog.ui
│   ├── staffregister_dialog.ui
│   ├── stockquery_dialog.ui
│   └── varietymenudialog.ui
├── res.qrc
├── samples
├── src
│   ├── include
│   │   ├── add_reduce_dialog.h
│   │   ├── check_outdialog.h
│   │   ├── dayincomequery_dialog.h
│   │   ├── daystatistics.h
│   │   ├── dishescountdialog.h
│   │   ├── foodinfo_dialog.h
│   │   ├── logindialog.h
│   │   ├── mainwindow.h
│   │   ├── monthincomequery_dialog.h
│   │   ├── orderdishesdialog.h
│   │   ├── selectseatdialog.h
│   │   ├── staffregister_dialog.h
│   │   ├── stockqquery_dialog.h
│   │   └── varietymenudialog.h
│   └── source
│   ├── add_reduce_dialog.cpp
│   ├── check_outdialog.cpp
│   ├── dayincomequery_dialog.cpp
│   ├── daystatistics.cpp
│   ├── dishescountdialog.cpp
│   ├── foodinfo_dialog.cpp
│   ├── logindialog.cpp
│   ├── main.cpp
│   ├── mainwindow.cpp
│   ├── monthincomequery_dialog.cpp
│   ├── orderdishesdialog.cpp
│   ├── selectseatdialog.cpp
│   ├── staffregister_dialog.cpp
│   ├── stockqquery_dialog.cpp
│   └── varietymenudialog.cpp
└── tools
```
...@@ -20,7 +20,7 @@ BIN_DIR=${BASE_DIR}/bin ...@@ -20,7 +20,7 @@ BIN_DIR=${BASE_DIR}/bin
LIB_DIR=${BASE_DIR}/lib LIB_DIR=${BASE_DIR}/lib
# 配置sqlite3驱动环境变量 # 配置sqlite3驱动环境变量
export LD_LIBRARY_PATH=${LIB_DIR}/sqlite3:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=${LIB_DIR}/sqlite3:${LIB_DIR}/log4qt:$LD_LIBRARY_PATH
# 启动程序 # 启动程序
${BIN_DIR}/${APP_NAME} ${BIN_DIR}/${APP_NAME}
......
PROJECT_ROOT = $$PWD
BUILD_DIST = $$PROJECT_ROOT/bin
APP_TARGET = rms
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_APPENDER_H
#define LOG4QT_APPENDER_H
#include "layout.h"
#include "log4qtsharedptr.h"
#include "spi/filter.h"
#include "helpers/classlogger.h"
namespace Log4Qt
{
class LoggingEvent;
/*!
* \brief The class Appender is the base class for all Appenders.
*
* To allow the whole hirarchy to be an ascendant of QObject Appender is
* not an interface.
*
* \note All the functions declared in this class are thread-safe.
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LOG4QT_EXPORT Appender : public QObject
{
Q_OBJECT
/*!
* The property holds the Layout used by the Appender.
*
* \sa layout(), setLayout()
*/
Q_PROPERTY(LayoutSharedPtr layout READ layout WRITE setLayout)
/*!
* The property holds the name of the Appender.
*
* \sa name(), setName()
*/
Q_PROPERTY(QString name READ name WRITE setName)
/*!
* The property holds if the Appender requires a Layout or not.
*
* \sa requiresLayout(), setRequiresLayout()
*/
Q_PROPERTY(bool requiresLayout READ requiresLayout)
public:
Appender(QObject *parent = nullptr);
virtual ~Appender();
virtual FilterSharedPtr filter() const = 0;
virtual QString name() const = 0;
virtual LayoutSharedPtr layout() const = 0;
virtual bool requiresLayout() const = 0;
virtual void setLayout(const LayoutSharedPtr &layout) = 0;
virtual void setName(const QString &name) = 0;
virtual void addFilter(const FilterSharedPtr &filter) = 0;
virtual void clearFilters() = 0;
virtual void close() = 0;
virtual void doAppend(const LoggingEvent &event) = 0;
protected:
/*!
* Returns a pointer to a Logger named after of the object.
*
* \sa Logger::logger()
*/
Logger *logger() const;
private:
Q_DISABLE_COPY(Appender)
mutable ClassLogger mLog4QtClassLogger;
};
using AppenderSharedPtr = Log4QtSharedPtr<Appender>;
} // namespace Log4Qt
#endif // LOG4QT_APPENDER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_APPENDERSKELETON_H
#define LOG4QT_APPENDERSKELETON_H
#include "appender.h"
#include "log4qtshared.h"
#include "layout.h"
#include "spi/filter.h"
#include "logger.h"
#include <QMutex>
namespace Log4Qt
{
class Logger;
class LoggingEvent;
/*!
* \brief The class AppenderSkeleton implements general Appender functionality.
*
* \note All the functions declared in this class are thread-safe.
*
* \note The ownership and lifetime of objects of this class are managed. See
* \ref Ownership "Object ownership" for more details.
*/
class LOG4QT_EXPORT AppenderSkeleton : public Appender
{
Q_OBJECT
/*!
* The property holds if the Appender has been activated.
*
* \sa isActive()
*/
Q_PROPERTY(bool isActive READ isActive)
/*!
* The property holds if the Appender has been closed.
*
* \sa isClosed()
*/
Q_PROPERTY(bool isClosed READ isClosed)
/*!
* The property holds the threshold level used by the Appender.
*
* \sa threshold(), setThreshold()
*/
Q_PROPERTY(Log4Qt::Level threshold READ threshold WRITE setThreshold)
public:
explicit AppenderSkeleton(QObject *parent = nullptr);
protected:
explicit AppenderSkeleton(bool isActive,
QObject *parent = nullptr);
explicit AppenderSkeleton(bool isActive,
const LayoutSharedPtr &layout,
QObject *parent = nullptr);
~AppenderSkeleton() override;
public:
FilterSharedPtr filter() const override;
LayoutSharedPtr layout() const override;
bool isActive() const;
bool isClosed() const;
QString name() const override;
Level threshold() const;
void setLayout(const LayoutSharedPtr &layout) override;
void setName(const QString &name) override;
void setThreshold(Level level);
virtual void activateOptions();
void addFilter(const FilterSharedPtr &filter) override;
void clearFilters() override;
void close() override;
/*!
* Performs checks and delegates the actuall appending to the subclass
* specific append() function.
*
* \sa append(), checkEntryConditions(), isAsSevereAsThreshold(), Filter
*/
void doAppend(const LoggingEvent &event) override;
FilterSharedPtr firstFilter() const;
bool isAsSevereAsThreshold(Level level) const;
protected:
virtual void append(const LoggingEvent &event) = 0;
void customEvent(QEvent *event) override;
/*!
* Tests if all entry conditions for using append() in this class are
* met.
*
* If a conditions is not met, an error is logged and the function
* returns false.
*
* The checked conditions are:
* - That the appender has been activated (APPENDER_NOT_ACTIVATED_ERROR)
* - That the appender was not closed (APPENDER_CLOSED_ERROR)
* - That the appender has a layout set, if it requires one
* (logging_error(APPENDER_USE_MISSING_LAYOUT_ERROR)
*
* The function is called as part of the checkEntryConditions() chain
* started by doAppend(). The doAppend() function calls the subclass
* specific checkEntryConditions() function. The function checks the
* class specific conditions and calls checkEntryConditions() of
* it's parent class. The last function called is
* AppenderSkeleton::checkEntryConditions().
*
* \sa doAppend()
*/
virtual bool checkEntryConditions() const;
protected:
#if QT_VERSION < 0x050E00
mutable QMutex mObjectGuard;
#else
mutable QRecursiveMutex mObjectGuard;
#endif
private:
Q_DISABLE_COPY(AppenderSkeleton)
bool mAppendRecursionGuard;
volatile bool mIsActive;
volatile bool mIsClosed;
LayoutSharedPtr mpLayout;
Level mThreshold;
FilterSharedPtr mpHeadFilter;
FilterSharedPtr mpTailFilter;
void closeInternal();
};
inline FilterSharedPtr AppenderSkeleton::filter() const
{
QMutexLocker locker(&mObjectGuard);
return mpHeadFilter;
}
inline QString AppenderSkeleton::name() const
{
QMutexLocker locker(&mObjectGuard);
return objectName();
}
inline Level AppenderSkeleton::threshold() const
{
return mThreshold;
}
inline void AppenderSkeleton::setName(const QString &name)
{
QMutexLocker locker(&mObjectGuard);
setObjectName(name);
}
inline void AppenderSkeleton::setThreshold(Level level)
{
mThreshold = level;
}
inline bool AppenderSkeleton::isActive() const
{
return mIsActive;
}
inline bool AppenderSkeleton::isClosed() const
{
return mIsClosed;
}
inline FilterSharedPtr AppenderSkeleton::firstFilter() const
{
QMutexLocker locker(&mObjectGuard);
return filter();
}
inline bool AppenderSkeleton::isAsSevereAsThreshold(Level level) const
{
return (mThreshold <= level);
}
} // namespace Log4Qt
#endif // LOG4QT_APPENDERSKELETON_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_ASYNCAPPENDER_H
#define LOG4QT_ASYNCAPPENDER_H
#include "appenderskeleton.h"
#include "helpers/appenderattachable.h"
namespace Log4Qt
{
class Dispatcher;
/*!
* \brief The class AsyncAppender lets users log events asynchronously.
*
* The AsyncAppender will collect the events sent to it and then dispatch them to all the
* appenders that are attached to it. You can attach multiple appenders to an AsyncAppender.
*
* The AsyncAppender uses a separate thread to serve the events fromthe event loop.
*
* \note All the functions declared in this class are thread-safe.
* &nbsp;
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LOG4QT_EXPORT AsyncAppender : public AppenderSkeleton, public AppenderAttachable
{
Q_OBJECT
public:
AsyncAppender(QObject *parent = nullptr);
~AsyncAppender() override;
bool requiresLayout() const override;
void activateOptions() override;
void close() override;
void callAppenders(const LoggingEvent &event) const;
/*!
* Tests if all entry conditions for using append() in this class are
* met.
*
* If a conditions is not met, an error is logged and the function
* returns false. Otherwise the result of
* AppenderSkeleton::checkEntryConditions() is returned.
*
* The checked conditions are:
* - dispatcher thread running (APPENDER_ASNC_DISPATCHER_NOT_RUNNING)
*
* The function is called as part of the checkEntryConditions() chain
* started by AppenderSkeleton::doAppend().
*
* \sa AppenderSkeleton::doAppend(),
* AppenderSkeleton::checkEntryConditions()
*/
bool checkEntryConditions() const override;
protected:
void append(const LoggingEvent &event) override;
private:
Q_DISABLE_COPY(AsyncAppender)
//! Event dispatcher trhead
QThread *mThread;
Dispatcher *mDispatcher;
void closeInternal();
};
} // namespace Log4Qt
#endif // LOG4QT_AsyncAppender_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_BASICCONFIGURATOR_H
#define LOG4QT_BASICCONFIGURATOR_H
#include "log4qt.h"
namespace Log4Qt
{
class Appender;
/*!
* \brief The class BasicConfigurator provides a simple package
* configuration.
*
* \note All the functions declared in this class are thread-safe.
*/
class LOG4QT_EXPORT BasicConfigurator
{
private:
Q_DISABLE_COPY(BasicConfigurator)
public:
static bool configure();
static void configure(Appender *pAppender);
static void resetConfiguration();
};
} // namspace
#endif // _BASICCONFIGURATOR_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_BINARYFILEAPPENDER_H
#define LOG4QT_BINARYFILEAPPENDER_H
#include "binarywriterappender.h"
#include <QDataStream>
class QFile;
namespace Log4Qt
{
class LOG4QT_EXPORT BinaryFileAppender : public BinaryWriterAppender
{
Q_OBJECT
Q_PROPERTY(bool appendFile READ appendFile WRITE setAppendFile)
Q_PROPERTY(bool bufferedIo READ bufferedIo WRITE setBufferedIo)
Q_PROPERTY(QString file READ file WRITE setFile)
Q_PROPERTY(QDataStream::ByteOrder byteOrder READ byteOrder WRITE setByteOrder)
Q_PROPERTY(QDataStream::FloatingPointPrecision floatingPointPrecision READ floatingPointPrecision WRITE setFloatingPointPrecision)
Q_PROPERTY(QDataStream::Version streamVersion READ streamVersion WRITE setStreamVersion)
public:
explicit BinaryFileAppender(QObject *parent = nullptr);
BinaryFileAppender(const QString &fileName,
QObject *parent = nullptr);
BinaryFileAppender(const QString &fileName,
bool append,
QObject *parent = nullptr);
BinaryFileAppender(const QString &fileName,
bool append,
bool buffered,
QObject *parent = nullptr);
virtual ~BinaryFileAppender();
// properties
bool appendFile() const;
void setAppendFile(bool append);
bool bufferedIo() const;
void setBufferedIo(bool buffered);
QString file() const;
void setFile(const QString &fileName);
QDataStream::ByteOrder byteOrder() const;
void setByteOrder(QDataStream::ByteOrder byteorder);
QDataStream::FloatingPointPrecision floatingPointPrecision() const;
void setFloatingPointPrecision(QDataStream::FloatingPointPrecision floatingpointprecision);
QDataStream::Version streamVersion() const;
void setStreamVersion(QDataStream::Version version);
// public members
void activateOptions() override;
void close() override;
protected:
bool checkEntryConditions() const override;
bool handleIoErrors() const override;
void closeFile();
void openFile();
bool removeFile(QFile &file) const;
bool renameFile(QFile &file, const QString &fileName) const;
private:
BinaryFileAppender(const BinaryFileAppender &other); // Not implemented
BinaryFileAppender &operator=(const BinaryFileAppender &other); // Not implemented
void createDataStream();
volatile bool mAppendFile;
volatile bool mBufferedIo;
QString mFileName;
QFile *mFile;
QDataStream *mDataStream;
QDataStream::ByteOrder mByteOrder;
QDataStream::FloatingPointPrecision mFloatingPointPrecision;
QDataStream::Version mStreamVersion;
void closeInternal();
};
inline bool BinaryFileAppender::appendFile() const
{
return mAppendFile;
}
inline QString BinaryFileAppender::file() const
{
QMutexLocker locker(&mObjectGuard);
return mFileName;
}
inline bool BinaryFileAppender::bufferedIo() const
{
return mBufferedIo;
}
inline void BinaryFileAppender::setAppendFile(bool append)
{
mAppendFile = append;
}
inline void BinaryFileAppender::setBufferedIo(bool buffered)
{
mBufferedIo = buffered;
}
inline void BinaryFileAppender::setFile(const QString &fileName)
{
QMutexLocker locker(&mObjectGuard);
mFileName = fileName;
}
inline QDataStream::ByteOrder BinaryFileAppender::byteOrder() const
{
return mByteOrder;
}
inline void BinaryFileAppender::setByteOrder(QDataStream::ByteOrder byteorder)
{
mByteOrder = byteorder;
}
inline QDataStream::FloatingPointPrecision BinaryFileAppender::floatingPointPrecision() const
{
return mFloatingPointPrecision;
}
inline void BinaryFileAppender::setFloatingPointPrecision(QDataStream::FloatingPointPrecision floatingpointprecision)
{
mFloatingPointPrecision = floatingpointprecision;
}
inline QDataStream::Version BinaryFileAppender::streamVersion() const
{
return mStreamVersion;
}
inline void BinaryFileAppender::setStreamVersion(QDataStream::Version version)
{
mStreamVersion = version;
}
} // namespace Log4Qt
#endif // LOG4QT_BINARYFILEAPPENDER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_BINARYLAYOUT_H
#define LOG4QT_BINARYLAYOUT_H
#include "layout.h"
#include <QByteArray>
namespace Log4Qt
{
class LoggingEvent;
class BinaryLoggingEvent;
class LOG4QT_EXPORT BinaryLayout : public Layout
{
Q_OBJECT
Q_PROPERTY(QByteArray binaryFooter READ binaryFooter WRITE setBinaryFooter)
Q_PROPERTY(QByteArray binaryHeader READ binaryHeader WRITE setBinaryHeader)
public:
explicit BinaryLayout(QObject *parent = nullptr);
virtual QByteArray binaryFormat(const BinaryLoggingEvent &event) const;
virtual QString format(const LoggingEvent &event) override;
virtual QString contentType() const override;
virtual QByteArray binaryFooter() const;
void setBinaryFooter(const QByteArray &footer);
virtual QByteArray binaryHeader() const;
void setBinaryHeader(const QByteArray &header);
private:
Q_DISABLE_COPY(BinaryLayout)
QByteArray mFooter;
QByteArray mHeader;
};
inline QByteArray BinaryLayout::binaryFooter() const
{
return mFooter;
}
inline void BinaryLayout::setBinaryFooter(const QByteArray &footer)
{
mFooter = footer;
}
inline QByteArray BinaryLayout::binaryHeader() const
{
return mHeader;
}
inline void BinaryLayout::setBinaryHeader(const QByteArray &header)
{
mHeader = header;
}
} // namespace Log4Qt
#endif // LOG4QT_BINARYLAYOUT_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_BINARYLOGGER_H
#define LOG4QT_BINARYLOGGER_H
#include "logger.h"
#include "binarylogstream.h"
#include "helpers/binaryclasslogger.h"
class QByteArray;
namespace Log4Qt
{
class Appender;
class BinaryLoggingEvent;
class LoggerRepository;
class Hierarchy;
#define LOG4QT_DECLARE_STATIC_BINARYLOGGER(FUNCTION, CLASS) \
static Log4Qt::BinaryLogger *FUNCTION() \
{ \
static Log4Qt::Logger * p_logger(Log4Qt::Logger::logger(#CLASS"@@binary@@" )); \
return qobject_cast<Log4Qt::BinaryLogger*>(p_logger); \
}
#define LOG4QT_DECLARE_QCLASS_BINARYLOGGER \
private: \
mutable Log4Qt::BinaryClassLogger mLog4QtClassLogger; \
public: \
inline Log4Qt::BinaryLogger *logger() const \
{ \
return mLog4QtClassLogger.logger(this); \
} \
private:
class LOG4QT_EXPORT BinaryLogger : public Logger
{
Q_OBJECT
public:
BinaryLogStream debug() const {return log(Level::DEBUG_INT);}
void debug(const QByteArray &message) const {log(Level::DEBUG_INT, message);}
BinaryLogStream error() const {return log(Level::ERROR_INT);}
void error(const QByteArray &message) const {log(Level::ERROR_INT, message);}
BinaryLogStream fatal() const {return log(Level::FATAL_INT);}
void fatal(const QByteArray &message) const {log(Level::FATAL_INT, message);}
BinaryLogStream info() const {return log(Level::INFO_INT);}
void info(const QByteArray &message) const {log(Level::INFO_INT, message);}
BinaryLogStream trace() const {return log(Level::TRACE_INT);}
void trace(const QByteArray &message) const {log(Level::TRACE_INT, message);}
BinaryLogStream warn() const {return log(Level::WARN_INT);}
void warn(const QByteArray &message) const {log(Level::WARN_INT, message);}
BinaryLogStream log(Level level) const;
void log(Level level, const QByteArray &message) const;
void log(Level level, const QByteArray &message, QDateTime timeStamp) const;
protected:
BinaryLogger(LoggerRepository *loggerRepository, Level level, const QString &name, Logger *parent = nullptr);
virtual ~BinaryLogger();
void forcedLog(Level level, const QByteArray &message) const;
private:
BinaryLogger(const BinaryLogger &other); // Not implemented
BinaryLogger &operator=(const BinaryLogger &other); // Not implemented
// Needs to be friend to create BinaryLogger objects
friend class Hierarchy;
};
} // namespace Log4Qt
#endif // LOG4QT_BINARYLOGGER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_BINARYLOGGINGEVENT_H
#define LOG4QT_BINARYLOGGINGEVENT_H
#include "loggingevent.h"
namespace Log4Qt
{
class LOG4QT_EXPORT BinaryLoggingEvent : public LoggingEvent
{
public:
BinaryLoggingEvent();
BinaryLoggingEvent(const Logger *logger,
Level level,
const QByteArray &message);
BinaryLoggingEvent(const Logger *logger,
Level level,
const QByteArray &message,
qint64 timeStamp);
BinaryLoggingEvent(const Logger *logger,
Level level,
const QByteArray &message,
const QString &ndc,
const QHash<QString, QString> &properties,
const QString &threadName,
qint64 timeStamp);
QByteArray binaryMessage() const;
QString toString() const;
static QString binaryMarker();
private:
QByteArray mBinaryMessage;
#ifndef QT_NO_DATASTREAM
// Needs to be friend to stream objects
friend LOG4QT_EXPORT QDataStream &operator<<(QDataStream &out, const BinaryLoggingEvent &loggingEvent);
friend LOG4QT_EXPORT QDataStream &operator>>(QDataStream &in, BinaryLoggingEvent &loggingEvent);
#endif // QT_NO_DATASTREAM
};
#ifndef QT_NO_DATASTREAM
LOG4QT_EXPORT QDataStream &operator<<(QDataStream &out, const BinaryLoggingEvent &loggingEvent);
LOG4QT_EXPORT QDataStream &operator>>(QDataStream &in, BinaryLoggingEvent &loggingEvent);
#endif // QT_NO_DATASTREAM
} // namespace Log4Qt
Q_DECLARE_METATYPE(Log4Qt::BinaryLoggingEvent)
Q_DECLARE_TYPEINFO(Log4Qt::BinaryLoggingEvent, Q_MOVABLE_TYPE);
#endif // LOG4QT_BINARYLOGGINGEVENT_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_BINARYLOGSTREAM_H
#define LOG4QT_BINARYLOGSTREAM_H
#include <QSharedPointer>
#include "level.h"
class QByteArray;
namespace Log4Qt
{
class Logger;
class LOG4QT_EXPORT BinaryLogStream
{
public:
BinaryLogStream(const Logger *logger, Level level);
BinaryLogStream &operator<<(const QByteArray &data);
private:
struct Stream;
QSharedPointer<Stream> mStream;
};
} // namespace Log4Qt
#endif // LOG4QT_BINARYLOGSTREAM_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_BINARYTOTEXTLAYOUT_H
#define LOG4QT_BINARYTOTEXTLAYOUT_H
#include "layout.h"
namespace Log4Qt
{
//! Used to format binary messages for a textual appenders
class LOG4QT_EXPORT BinaryToTextLayout : public Layout
{
Q_OBJECT
Q_PROPERTY(LayoutSharedPtr subLayout READ subLayout WRITE setSubLayout)
public:
explicit BinaryToTextLayout(const LayoutSharedPtr &subLayout = LayoutSharedPtr(), QObject *parent = nullptr);
virtual QString format(const LoggingEvent &event) override;
LayoutSharedPtr subLayout() const {return mSubLayout;}
void setSubLayout(const LayoutSharedPtr &layout) {mSubLayout = layout;}
private:
Q_DISABLE_COPY(BinaryToTextLayout)
LayoutSharedPtr mSubLayout;
};
} // namespace Log4Qt
#endif // LOG4QT_BINARYTOTEXTLAYOUT_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_BINARYWRITTERAPPENDER_H
#define LOG4QT_BINARYWRITTERAPPENDER_H
#include "appenderskeleton.h"
class QDataStream;
namespace Log4Qt
{
class BinaryLayout;
class LOG4QT_EXPORT BinaryWriterAppender : public AppenderSkeleton
{
Q_OBJECT
Q_PROPERTY(QDataStream *writer READ writer WRITE setWriter)
public:
BinaryWriterAppender(QObject *parent = nullptr);
BinaryWriterAppender(QDataStream *dataStream, QObject *parent = nullptr);
~BinaryWriterAppender() override;
bool requiresLayout() const override;
QDataStream *writer() const;
void setWriter(QDataStream *dataStream);
void activateOptions() override;
void close() override;
protected:
void append(const LoggingEvent &event) override;
bool checkEntryConditions() const override;
void closeWriter();
virtual bool handleIoErrors() const;
void writeFooter() const;
void writeHeader() const;
private:
Q_DISABLE_COPY(BinaryWriterAppender)
void writeRawData(const QByteArray &data) const;
void closeInternal();
BinaryLayout *binaryLayout() const;
QDataStream *mWriter;
};
inline QDataStream *BinaryWriterAppender::writer() const
{
return mWriter;
}
} // namespace Log4Qt
#endif // LOG4QT_BINARYWRITTERAPPENDER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_CONSOLEAPPENDER_H
#define LOG4QT_CONSOLEAPPENDER_H
#include "writerappender.h"
class QTextStream;
namespace Log4Qt
{
/*!
* \brief The class ConsoleAppender appends to stdout or stderr.
*
* \note All the functions declared in this class are thread-safe.
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LOG4QT_EXPORT ConsoleAppender : public WriterAppender
{
Q_OBJECT
/*!
* The property holds the target used by the appender.
*
* The default is STDOUT_TARGET for the standard output.
*
* \sa Target, target(), setTarget()
*/
Q_PROPERTY(QString target READ target WRITE setTarget)
public:
/*!
* The enum defines the possible output targets
*
* \sa target(), setTarget()
*/
enum Target
{
/*! The output target is standard out. */
STDOUT_TARGET,
/*! The output target is standard error. */
STDERR_TARGET
};
Q_ENUM(Target)
ConsoleAppender(QObject *parent = nullptr);
ConsoleAppender(const LayoutSharedPtr &pLayout,
QObject *parent = nullptr);
ConsoleAppender(const LayoutSharedPtr &pLayout,
const QString &target,
QObject *parent = nullptr);
/*!
* Creates a ConsoleAppender with the layout \a pLayout, the target
* value specified by the \a target constant and the parent
* \a parent.
*/
ConsoleAppender(const LayoutSharedPtr &pLayout,
Target target,
QObject *parent = nullptr);
~ConsoleAppender() override;
private:
Q_DISABLE_COPY(ConsoleAppender)
public:
QString target() const;
void setTarget(const QString &target);
/*!
* Sets the target to the value specified by the \a target constant.
*/
void setTarget(Target target);
virtual void activateOptions() override;
virtual void close() override;
protected:
void closeStream();
private:
volatile Target mTarget;
QTextStream *mtextStream;
void closeInternal();
};
inline void ConsoleAppender::setTarget(Target target)
{
mTarget = target;
}
} // namespace Log4Qt
#endif // _CONSOLEAPPENDER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_DAILYFILEAPPENDER_H
#define LOG4QT_DAILYFILEAPPENDER_H
#include "fileappender.h"
#include <QDate>
#include <QFutureSynchronizer>
#include <QSharedPointer>
#include <QString>
namespace Log4Qt
{
class LOG4QT_EXPORT IDateRetriever
{
public:
virtual ~IDateRetriever();
virtual QDate currentDate() const = 0;
};
class LOG4QT_EXPORT DefaultDateRetriever final : public IDateRetriever
{
public:
/**
* Return the current date, as reported by the system clock.
*/
QDate currentDate() const override;
};
/*!
* \brief The class DailyFileAppender extends FileAppender so that the
* a log file is created for each day
*/
class LOG4QT_EXPORT DailyFileAppender : public FileAppender
{
Q_OBJECT
//! The property holds the date pattern used by the appender.
Q_PROPERTY(QString datePattern READ datePattern WRITE setDatePattern)
/**
* Number of days that old log files will be kept on disk.
* Set to a positive value to enable automatic deletion. Per default, all files are kept. Check
* for obsolete files happens once a day.
*/
Q_PROPERTY(int keepDays READ keepDays WRITE setKeepDays)
public:
explicit DailyFileAppender(QObject *parent = nullptr);
DailyFileAppender(const LayoutSharedPtr &layout, const QString &fileName, const QString &datePattern = QString(), int keepDays = 0, QObject *parent = nullptr);
QString datePattern() const;
void setDatePattern(const QString &datePattern);
int keepDays() const;
void setKeepDays(int keepDays);
void activateOptions() override;
void append(const LoggingEvent &event) override;
void setDateRetriever(const QSharedPointer<const IDateRetriever> &dateRetriever);
private:
Q_DISABLE_COPY(DailyFileAppender)
void setLogFileForCurrentDay();
void rollOver();
QString appendDateToFilename() const;
QSharedPointer<const IDateRetriever> mDateRetriever;
QString mDatePattern;
QDate mLastDate;
int mKeepDays;
QString mOriginalFilename;
QFutureSynchronizer<void> mDeleteObsoleteFilesExecutors;
};
}
#endif // LOG4QT_DAILYFILEAPPENDER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_DAILYROLLINGFILEAPPENDER_H
#define LOG4QT_DAILYROLLINGFILEAPPENDER_H
#include "fileappender.h"
#include <QDateTime>
namespace Log4Qt
{
/*!
* \brief The class DailyRollingFileAppender extends FileAppender so that the
* underlying file is rolled over at a specified frequency.
*
* \note All the functions declared in this class are thread-safe.
*
* \note The ownership and lifetime of objects of this class are managed. See
* \ref Ownership "Object ownership" for more details.
*/
class LOG4QT_EXPORT DailyRollingFileAppender : public FileAppender
{
Q_OBJECT
/*!
* The property holds the date pattern used by the appender.
*
* The default is DAILY_ROLLOVER for rollover at midnight each day.
*
* \sa datePattern(), setDatePattern()
*/
Q_PROPERTY(QString datePattern READ datePattern WRITE setDatePattern)
public:
/*!
* The enum DatePattern defines constants for date patterns.
*
* \sa setDatePattern(DatePattern)
*/
enum DatePattern
{
/*! The minutely date pattern string is "'.'yyyy-MM-dd-hh-mm". */
MINUTELY_ROLLOVER = 0,
/*! The hourly date pattern string is "'.'yyyy-MM-dd-hh". */
HOURLY_ROLLOVER,
/*! The half-daily date pattern string is "'.'yyyy-MM-dd-a". */
HALFDAILY_ROLLOVER,
/*! The daily date pattern string is "'.'yyyy-MM-dd". */
DAILY_ROLLOVER,
/*! The weekly date pattern string is "'.'yyyy-ww". */
WEEKLY_ROLLOVER,
/*! The monthly date pattern string is "'.'yyyy-MM". */
MONTHLY_ROLLOVER
};
Q_ENUM(DatePattern)
DailyRollingFileAppender(QObject *parent = nullptr);
DailyRollingFileAppender(const LayoutSharedPtr &layout,
const QString &fileName,
const QString &datePattern,
QObject *parent = nullptr);
private:
Q_DISABLE_COPY(DailyRollingFileAppender)
public:
QString datePattern() const;
/*!
* Sets the datePattern to the value specified by the \a datePattern
* constant.
*/
void setDatePattern(DatePattern datePattern);
void setDatePattern(const QString &datePattern);
void activateOptions() override;
protected:
void append(const LoggingEvent &event) override;
/*!
* Tests if all entry conditions for using append() in this class are
* met.
*
* If a conditions is not met, an error is logged and the function
* returns false. Otherwise the result of
* FileAppender::checkEntryConditions() is returned.
*
* The checked conditions are:
* - A valid pattern has been set (APPENDER_USE_INVALID_PATTERN_ERROR)
*
* The function is called as part of the checkEntryConditions() chain
* started by AppenderSkeleton::doAppend().
*
* \sa AppenderSkeleton::doAppend(),
* AppenderSkeleton::checkEntryConditions()
*/
bool checkEntryConditions() const override;
private:
void computeFrequency();
void computeRollOvetime();
QString frequencyToString() const;
void rollOver();
private:
QString mDatePattern;
DatePattern mFrequency;
QString mActiveDatePattern;
QDateTime mRollOvetime;
QString mRollOverSuffix;
};
inline QString DailyRollingFileAppender::datePattern() const
{
QMutexLocker locker(&mObjectGuard);
return mDatePattern;
}
inline void DailyRollingFileAppender::setDatePattern(const QString &datePattern)
{
QMutexLocker locker(&mObjectGuard);
mDatePattern = datePattern;
}
} // namespace Log4Qt
#endif // LOG4QT_DAILYROLLINGFILEAPPENDER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_FILEAPPENDER_H
#define LOG4QT_FILEAPPENDER_H
#include "writerappender.h"
class QFile;
class QTextStream;
namespace Log4Qt
{
/*!
* \brief The class FileAppender appends log events to a file.
*
* \note All the functions declared in this class are thread-safe.
*
* \note The ownership and lifetime of objects of this class are managed. See
* \ref Ownership "Object ownership" for more details.
*/
class LOG4QT_EXPORT FileAppender : public WriterAppender
{
Q_OBJECT
/*!
* The property holds, if the output is appended to the file.
*
* The default is false for not appending.
*
* \sa appendFile(), setAppendFile()
*/
Q_PROPERTY(bool appendFile READ appendFile WRITE setAppendFile)
/*!
* The property holds, if the output is buffered.
*
* The default is true for buffering.
*
* \sa bufferedIo(), setBufferedIo()
*/
Q_PROPERTY(bool bufferedIo READ bufferedIo WRITE setBufferedIo)
/*!
* The property holds the name of the file.
*
* \sa file(), setFile()
*/
Q_PROPERTY(QString file READ file WRITE setFile)
public:
explicit FileAppender(QObject *parent = nullptr);
FileAppender(const LayoutSharedPtr &layout,
const QString &fileName,
QObject *parent = nullptr);
FileAppender(const LayoutSharedPtr &layout,
const QString &fileName,
bool append,
QObject *parent = nullptr);
FileAppender(const LayoutSharedPtr &layout,
const QString &fileName,
bool append,
bool buffered,
QObject *parent = nullptr);
~FileAppender() override;
private:
Q_DISABLE_COPY(FileAppender)
public:
bool appendFile() const;
QString file() const;
bool bufferedIo() const;
void setAppendFile(bool append);
void setBufferedIo(bool buffered);
void setFile(const QString &fileName);
void activateOptions() override;
void close() override;
protected:
/*!
* Tests if all entry conditions for using append() in this class are met.
*
* If a conditions is not met, an error is logged and the function returns
* false. Otherwise the result of WriterAppender::checkEntryConditions()
* is returned.
*
* The checked conditions are:
* - That a file is set and open (APPENDER_NO_OPEN_FILE_ERROR)
*
* The function is called as part of the checkEntryConditions() chain
* started by AppenderSkeleton::doAppend().
*
* \sa AppenderSkeleton::doAppend(), AppenderSkeleton::checkEntryConditions()
*/
bool checkEntryConditions() const override;
void closeFile();
/*!
* Checks for file I/O errrors. If an error is found it is logged and the
* function returns true. Otherwise false is returned.
*/
bool handleIoErrors() const override;
/*!
* Opens the file for the appender based on the specified file name and
* mode. A text stream is created and passed on to the super class
* WriterAppender.
*
* If the parent directory of the specified file does not exists,
* it is created.
*/
virtual void openFile();
/*!
* Removes the file \a file. If the operation is successful, true is
* returned. Otherwise an APPENDER_REMOVE_FILE_ERROR error is logged
* and false is returned.
*/
bool removeFile(QFile &file) const;
/*!
* Renames the file \a file to \a fileName. If the operation is
* successful, true is returned. Otherwise an
* APPENDER_RENAMING_FILE_ERROR error is logged and false is returned.
*/
bool renameFile(QFile &file,
const QString &fileName) const;
private:
volatile bool mAppendFile;
volatile bool mBufferedIo;
QString mFileName;
QFile *mFile;
QTextStream *mTextStream;
void closeInternal();
};
inline bool FileAppender::appendFile() const
{
return mAppendFile;
}
inline QString FileAppender::file() const
{
QMutexLocker locker(&mObjectGuard);
return mFileName;
}
inline bool FileAppender::bufferedIo() const
{
return mBufferedIo;
}
inline void FileAppender::setAppendFile(bool append)
{
mAppendFile = append;
}
inline void FileAppender::setBufferedIo(bool buffered)
{
mBufferedIo = buffered;
}
inline void FileAppender::setFile(const QString &fileName)
{
QMutexLocker locker(&mObjectGuard);
mFileName = fileName;
}
} // namespace Log4Qt
#endif // LOG4QT_FILEAPPENDER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_APPENDERATTACHABLE_H
#define LOG4QT_APPENDERATTACHABLE_H
#include "log4qt/log4qt.h"
#include "log4qt/appender.h"
#include <QList>
#include <QReadWriteLock>
namespace Log4Qt
{
/*!
* \brief Implementation for attaching appenders to objects
*/
class LOG4QT_EXPORT AppenderAttachable
{
public:
AppenderAttachable();
virtual ~AppenderAttachable();
/*!
* Add an appender.
*/
virtual void addAppender(const AppenderSharedPtr &appender);
/*!
* Get all previously added appenders as an Enumeration.
*/
virtual QList<AppenderSharedPtr> appenders() const;
/*!
* Get an appender by name.
*/
virtual AppenderSharedPtr appender(const QString &name) const;
/*!
Returns <code>true</code> if the specified appender is in the
list of attached appenders, <code>false</code> otherwise.
*/
virtual bool isAttached(const AppenderSharedPtr &appender) const;
/*!
* Removes all appenders that have been previously added from this
* Logger.
*
* To allow configurators to collect events during the configuration
* process ListAppenders with the configuratorList property set, will
* not be removed.
*
* \sa LisAppender::setConfiguratorList()
*/
virtual void removeAllAppenders();
/*!
* Remove the appender passed as parameter from the list of appenders.
*/
virtual void removeAppender(const AppenderSharedPtr &appender);
/*!
* Remove the appender with the name passed as parameter from the
* list of appenders.
*/
virtual void removeAppender(const QString &name);
protected:
QList<AppenderSharedPtr> mAppenders;
mutable QReadWriteLock mAppenderGuard;
};
} // namespace Log4Qt
#endif // LOG4QT_APPENDERATTACHABLE_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_BINARYCLASSLOGGER_H
#define LOG4QT_BINARYCLASSLOGGER_H
#include "log4qt/log4qtshared.h"
#include <QAtomicPointer>
class QObject;
namespace Log4Qt
{
class Logger;
class BinaryLogger;
class LOG4QT_EXPORT BinaryClassLogger
{
public:
BinaryClassLogger();
BinaryLogger *logger(const QObject *object);
private:
mutable QAtomicPointer<BinaryLogger> mLogger;
};
} // namespace Log4Qt
#endif // LOG4QT_BINARYCLASSLOGGER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_CLASSLOGGER_H
#define LOG4QT_CLASSLOGGER_H
#include "log4qt/log4qtshared.h"
#include <QAtomicPointer>
class QObject;
namespace Log4Qt
{
class Logger;
/*!
* \brief The class ClassLogger provides logging for a QObject derived
* class.
*
* The class ClassLogger provides a logger for a specified QObject derived
* object. It is used by \ref LOG4QT_DECLARE_QCLASS_LOGGER to implement the
* member functions provided by the macro.
*
* \note All the functions declared in this class are thread-safe.
*
* \sa LOG4QT_DECLARE_QCLASS_LOGGER
*/
class LOG4QT_EXPORT ClassLogger
{
public:
/*!
* Creates a ClassLogger object.
*/
ClassLogger();
/*!
* Returns a pointer to a Logger named after the class of the object
* \a pObject.
*
* On the first invocation the Logger is requested by a call to
* LogManager::logger(const char *pName). The pointer is stored to be
* returned on subsequent invocations.
*
* \sa LogManager::logger(const char *pName)
*/
Logger *logger(const QObject *object);
private:
mutable QAtomicPointer<Logger> mLogger;
};
} // namespace Log4Qt
#endif // LOG4QT_CLASSLOGGER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_HELPERS_CONFIGURATORHELPER_H
#define LOG4QT_HELPERS_CONFIGURATORHELPER_H
#include "log4qt/log4qtshared.h"
#include "log4qt/loggingevent.h"
#include <QObject>
#include <QList>
#include <QMutex>
#include <QFileInfo>
class QFileSystemWatcher;
namespace Log4Qt
{
/*!
* \brief The class ConfiguratorHelper provides a confiuration file watch
* and last error for configurator classes.
*
* A configuration file can be set using setConfigurationFile(). The file
* is watched for changes. If a change occurs the configuration is reloaded
* and the ConfigurationFileChanged() signal is Q_EMITted. Error information
* for the last call to a configure function or the last configuration file
* change can be accessed using configureError().
*
* \note All the functions declared in this class are thread-safe.
*/
class LOG4QT_EXPORT ConfiguratorHelper : public QObject
{
Q_OBJECT
public:
/*!
* Prototype for a configure callback function. The function is called
* when then configuration file is changed and takes the
* configuration file as a parameter.
*
* \sa setConfigurationFile(),
* PropertyConfigurator::configure(const QString &)
*/
typedef bool (*ConfigureFunc)(const QString &fileName);
private:
ConfiguratorHelper(QObject *parent = nullptr);
virtual ~ConfiguratorHelper();
Q_DISABLE_COPY(ConfiguratorHelper)
public:
/*!
* Returns the error information for the last configuration operation
* that took place. The configuration operation could be the result of
* a call to one of the configure methods or through a change
* to the configuration file.
*
* \sa setConfigureError(), PropertyConfigurator::configure(),
* setConfigurationFile()
*/
static QList<LoggingEvent> configureError();
/*!
* Returns the current configuration file.
*
* \sa setConfigurationFile()
*/
static QString configurationFile();
/*!
* Returns the ConfiguratorHelper instance.
*/
static ConfiguratorHelper *instance();
/*!
* Sets the configuration error information for the last configuration
* operation.
*
* \sa configureError()
*/
static void setConfigureError(const QList<LoggingEvent> &configureError);
/*!
* Sets the configuration file to \a fileName. The file is watched for
* changes. On a file change the function \a pConfigureFunc will be called
* and the signal configurationFileChange() will be Q_EMITted.
*
* Setting the configuration file to an empty string stops the file watch.
*
* \sa configurationFile(), PropertyConfigurator::configureAndWatch(),
* configureError()
*/
static void setConfigurationFile(const QString &fileName = QString(),
ConfigureFunc pConfigureFunc = nullptr);
Q_SIGNALS:
/*!
* The signal is Q_EMITted after a change to the file \a fileName
* was processed. If an error occured during the configuration, the
* flag \a error will be true and error information is available
* over configureError().
*/
void configurationFileChanged(const QString &fileName,
bool error);
private Q_SLOTS:
void doConfigurationFileChanged(const QString &fileName);
void doConfigurationFileDirectoryChanged(const QString &path);
void tryToReAddConfigurationFile();
private:
void doSetConfigurationFile(const QString &fileName,
ConfigureFunc pConfigureFunc);
private:
mutable QMutex mObjectGuard;
QFileInfo mConfigurationFile;
ConfigureFunc mConfigureFunc;
QFileSystemWatcher *mConfigurationFileWatch;
QList<LoggingEvent> mConfigureError;
};
inline QList<LoggingEvent> ConfiguratorHelper::configureError()
{
QMutexLocker locker(&instance()->mObjectGuard);
return instance()->mConfigureError;
}
inline QString ConfiguratorHelper::configurationFile()
{
QMutexLocker locker(&instance()->mObjectGuard);
return instance()->mConfigurationFile.absoluteFilePath();
}
inline void ConfiguratorHelper::setConfigureError(const QList<LoggingEvent> &configureError)
{
QMutexLocker locker(&instance()->mObjectGuard);
instance()->mConfigureError = configureError;
}
inline void ConfiguratorHelper::setConfigurationFile(const QString &fileName,
ConfigureFunc pConfigureFunc)
{
instance()->doSetConfigurationFile(fileName, pConfigureFunc);
}
} // namespace Log4Qt
#endif // LOG4QT_HELPERS_CONFIGURATORHELPER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_HELPERS_DATETIME_H
#define LOG4QT_HELPERS_DATETIME_H
#include "log4qt/log4qtshared.h"
#include <QDateTime>
namespace Log4Qt
{
/*!
* \brief The class DateTime provides extended functionality for QDateTime.
*
* The class DateTime implements additional formatting options for
* toString() and provides conversion functions from and to milliseconds.
*/
class LOG4QT_EXPORT DateTime : public QDateTime
{
public:
/*!
* Constructs a null date time.
*
* \sa QDateTime::QDateTime()
*/
DateTime();
~DateTime();
/*!
* Constructs a copy of another QDateTime.
*
* \sa QDateTime::QDateTime(const QDateTime &other)
*/
DateTime(const QDateTime &other);
DateTime(const DateTime &other);
/*!
* Constructs a datetime with the given \a date and \a time, using
* the time specification defined by \a timeSpec.
*
* \sa QDateTime::QDateTime(const QDate &date, const QTime &time,
* Qt::TimeSpec timeSpec = Qt::LocalTime)
*/
DateTime(QDate date,
QTime time,
Qt::TimeSpec timeSpec = Qt::LocalTime);
/*!
* Assigns \a other to this DateTime and returns a reference to it.
*/
DateTime &operator=(const DateTime &other);
/*!
* Returns the datetime as a string. The \a format parameter
* determines the format of the result string.
*
*
* Alternatively the \a format parameter can specify one of the
* following strings.
*
* <table align="center" border="1" cellpadding="2" cellspacing="0" bordercolor="#84b0c7">
* <tr bgcolor="#d5e1e8">
* <th width="20%"> String </th>
* <th> Format </th>
* </tr><tr>
* <td> ABSOLUTE </td>
* <td> uses the format HH:mm:ss.zzz </td>
* </tr><tr bgcolor="#ffffff">
* <td> DATE </td>
* <td> uses the format dd MMM YYYY HH:mm:ss.zzz </td>
* </tr><tr>
* <td> ISO8601 </td>
* <td> uses the format yyyy-MM-dd hh:mm:ss.zzz </td>
* </tr><tr bgcolor="#ffffff">
* <td> NONE </td>
* <td> uses an empty string as format </td>
* </tr><tr bgcolor="#ffffff">
* <td> RELATIVE </td>
* <td> returns the milliseconds since start of the program</td>
* </tr>
* </table>
*
* \sa QDateTime::toString(const QString &format)
*/
QString toString(const QString &format) const;
/*!
* Returns the current datetime, as reported by the system clock, in
* the local time zone.
*
* \sa QDateTime::currentDateTime()
*/
static DateTime currentDateTime();
static DateTime fromMSecsSinceEpoch(qint64 msecs, Qt::TimeSpec spec, int offsetSeconds = 0);
static DateTime fromMSecsSinceEpoch(qint64 msecs);
private:
QString formatDateTime(const QString &format) const;
};
inline DateTime::DateTime(const QDateTime &other) : QDateTime(other)
{}
inline DateTime::DateTime(QDate date,
QTime time,
Qt::TimeSpec timeSpec) :
QDateTime(date, time, timeSpec)
{}
inline DateTime &DateTime::operator=(const DateTime &other)
{
QDateTime::operator=(other);
return *this;
}
inline DateTime DateTime::currentDateTime()
{
return DateTime(QDateTime::currentDateTime());
}
inline DateTime DateTime::fromMSecsSinceEpoch(qint64 msecs)
{
return DateTime(QDateTime::fromMSecsSinceEpoch(msecs));
}
inline DateTime DateTime::fromMSecsSinceEpoch(qint64 msecs, Qt::TimeSpec spec, int offsetSeconds)
{
return DateTime(QDateTime::fromMSecsSinceEpoch(msecs, spec, offsetSeconds));
}
} // namespace Log4Qt
Q_DECLARE_TYPEINFO(Log4Qt::DateTime, Q_MOVABLE_TYPE);
#endif // LOG4QT_HELPERS_DATETIME_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QTDISPATCHER_H
#define LOG4QTDISPATCHER_H
#include <QObject>
namespace Log4Qt
{
class AsyncAppender;
/*!
* \brief The class Dispatcher does the actual logging to the attached appanders.
*
* The Dispatcher is the worker object which class the attached apperders in the
* the context of the DispatcherThread.
*
* \note All the functions declared in this class are thread-safe.
*/
class Dispatcher : public QObject
{
Q_OBJECT
public:
explicit Dispatcher(QObject *parent = nullptr);
void setAsyncAppender(AsyncAppender *asyncAppender);
protected:
void customEvent(QEvent *event) override;
private:
AsyncAppender *mAsyncAppender;
};
} // namespace Log4Qt
#endif // DISPATCHER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_HELPERS_FACTORY_H
#define LOG4QT_HELPERS_FACTORY_H
#include "log4qt/log4qtshared.h"
#include <QHash>
#include <QMutex>
#include <QStringList>
class QObject;
class QMetaProperty;
namespace Log4Qt
{
class Appender;
class Filter;
class Layout;
/*!
* \brief The class Factory provides factories for Appender, Filter and
* Layout objects.
*
* The functions createAppender(), createFilter() and createLayout()
* allow to create objects by specifying their class names. By default
* all classes of the package are recognised with their Log4j and Log4Qt
* classanmes. For example an object of the class FileAppender can be
* craeted using "org.apache.log4j.FileAppender" or "Log4Qt::FileAppender".
* Additional classes can be registered using registerAppender(),
* registerFilter() and registerLayout().
*
* An QObject property can be set from a string value with
* setObjectProperty(). The function handles the required error checking
* and type conversion.
*
* \note All the functions declared in this class are thread-safe.
*
* \sa PropertyConfigurator
*/
class LOG4QT_EXPORT Factory
{
public:
/*!
* Prototype for an Appender factory function. The function creates
* an Appender object on the heap and returns a pointer to it.
*
* \sa registerAppender(), createAppender()
*/
typedef Appender *(*AppenderFactoryFunc)();
/*!
* Prototype for a Filter factory function. The function creates
* a Filter object on the heap and returns a pointer to it.
*
* \sa registerFilter(), createFilter()
*/
typedef Filter *(*FilterFactoryFunc)();
/*!
* Prototype for a Layout factory function. The function creates
* a Layout object on the heap and returns a pointer to it.
*
* \sa registerLayout(), createLayout()
*/
typedef Layout *(*LayoutFactoryFunc)();
private:
Factory();
Q_DISABLE_COPY(Factory)
public:
/*!
* Creates an object for the class \a appenderClassName on the heap
* and returns a pointer to it. If the class has no registered factory
* function a null pointer is returned.
*
* \sa registerAppender(), unregisterAppender(), registeredAppenders()
*/
static Appender *createAppender(const QString &appenderClassName);
/*!
* This is an overloaded member function, provided for convenience.
*/
static Appender *createAppender(const char *appenderClassName);
/*!
* Creates an object for the class \a filterClassName on the heap
* and returns a pointer to it. If the class has no registered factory
* function a null pointer is returned.
*
* \sa registerFilter(), unregisterFilter(), registeredFilters()
*/
static Filter *createFilter(const QString &filterClassName);
/*!
* This is an overloaded member function, provided for convenience.
*/
static Filter *createFilter(const char *filterClassName);
/*!
* Creates an object for the class \a layoutClassName on the heap
* and returns a pointer to it. If the class has no registered factory
* function a null pointer is returned.
*
* \sa registerLayout(), unregisterLayout(), registeredLayouts()
*/
static Layout *createLayout(const QString &layoutClassName);
/*!
* This is an overloaded member function, provided for convenience.
*/
static Layout *createLayout(const char *layoutClassName);
/*!
* Returns the Factory instance.
*/
static Factory *instance();
/*!
* Registers the Appender factory function \a appenderFactoryFunc
* for the class \a appenderClassName. If a registered factory
* function exists for the class, it is replaced with
* \a appenderFactoryFunc.
*
* \sa unregisterAppender(), registeredAppenders(), createAppender()
*/
static void registerAppender(const QString &appenderClassName,
AppenderFactoryFunc appenderFactoryFunc);
/*!
* This is an overloaded member function, provided for convenience.
*/
static void registerAppender(const char *appenderClassName,
AppenderFactoryFunc appenderFactoryFunc);
/*!
* Registers the Filter factory function \a filterFactoryFunc
* for the class \a filterClassName. If a registered factory
* function exists for the class, it is replaced with
* \a filterFactoryFunc.
*
* \sa unregisterFilter(), registeredFilters(), createFilter()
*/
static void registerFilter(const QString &filterClassName,
FilterFactoryFunc filterFactoryFunc);
/*!
* This is an overloaded member function, provided for convenience.
*/
static void registerFilter(const char *filterClassName,
FilterFactoryFunc filterFactoryFunc);
/*!
* Registers the Layout factory function \a layoutFactoryFunc
* for the class \a filterClassName. If a registered factory
* function exists for the class, it is replaced with
* \a layoutFactoryFunc.
*
* \sa unregisterLayout(), registeredLayout(), createLayout()
*/
static void registerLayout(const QString &layoutClassName,
LayoutFactoryFunc layoutFactoryFunc);
/*!
* This is an overloaded member function, provided for convenience.
*/
static void registerLayout(const char *layoutClassName,
LayoutFactoryFunc layoutFactoryFunc);
/*!
* Returns a list of the class names for registered Appender factory
* functions.
*
* \sa registerAppender(), unregisterAppender()
*/
static QStringList registeredAppenders();
/*!
* Returns a list of the class names for registered Filter factory
* functions.
*
* \sa registerFilter(), unregisterFilter()
*/
static QStringList registeredFilters();
/*!
* Returns a list of the class names for registered Layout factory
* functions.
*
* \sa registerLayout(), unregisterLayout()
*/
static QStringList registeredLayouts();
/*!
* Sets the property \a rProperty of the object \a pObject to the
* value \a rValue. The function will test that the property
* \a rProperty is writeable and of a type the function can convert to.
* The types bool, int, Level and QString are supported.
*
* \sa OptionConverter
*/
static void setObjectProperty(QObject *object,
const QString &property,
const QString &value);
/*!
* This is an overloaded member function, provided for convenience.
*/
static void setObjectProperty(QObject *object,
const char *property,
const QString &value);
/*!
* Unregisters the Appender factory function for the class
* \a rAppenderClassName.
*
* \sa registerAppender(), registeredAppenders()
*/
static void unregisterAppender(const QString &appenderClassName);
/*!
* This is an overloaded member function, provided for convenience.
*/
static void unregisterAppender(const char *appenderClassName);
/*!
* Unregisters the Filter factory function for the class
* \a filterClassName.
*
* \sa registerFilter(), registeredFilters()
*/
static void unregisterFilter(const QString &filterClassName);
/*!
* This is an overloaded member function, provided for convenience.
*/
static void unregisterFilter(const char *filterClassName);
/*!
* Unregisters the Layout factory function for the class
* \a filterClassName.
*
* \sa registerLayout(), registeredLayouts()
*/
static void unregisterLayout(const QString &filterClassName);
/*!
* This is an overloaded member function, provided for convenience.
*/
static void unregisterLayout(const char *layoutClassName);
private:
Appender *doCreateAppender(const QString &appenderClassName);
Filter *doCreateFilter(const QString &filterClassName);
Layout *doCreateLayout(const QString &layoutClassName);
void doRegisterAppender(const QString &appenderClassName,
AppenderFactoryFunc appenderFactoryFunc);
void doRegisterFilter(const QString &filterClassName,
FilterFactoryFunc filterFactoryFunc);
void doRegisterLayout(const QString &filterClassName,
LayoutFactoryFunc layoutFactoryFunc);
void doSetObjectProperty(QObject *object,
const QString &property,
const QString &value);
void doUnregisterAppender(const QString &appenderClassName);
void doUnregisterFilter(const QString &filterClassName);
void doUnregisterLayout(const QString &filterClassName);
void registerDefaultAppenders();
void registerDefaultFilters();
void registerDefaultLayouts();
bool validateObjectProperty(QMetaProperty &metaProperty,
const QString &property,
QObject *object);
private:
mutable QMutex mObjectGuard;
QHash<QString, AppenderFactoryFunc> mAppenderRegistry;
QHash<QString, FilterFactoryFunc> mFilterRegistry;
QHash<QString, LayoutFactoryFunc> mLayoutRegistry;
};
inline Appender *Factory::createAppender(const QString &appenderClassName)
{
return instance()->doCreateAppender(appenderClassName);
}
inline Appender *Factory::createAppender(const char *appenderClassName)
{
return instance()->doCreateAppender(QLatin1String(appenderClassName));
}
inline Filter *Factory::createFilter(const QString &filterClassName)
{
return instance()->doCreateFilter(filterClassName);
}
inline Filter *Factory::createFilter(const char *layoutClassName)
{
return instance()->doCreateFilter(QLatin1String(layoutClassName));
}
inline Layout *Factory::createLayout(const QString &layoutClassName)
{
return instance()->doCreateLayout(layoutClassName);
}
inline Layout *Factory::createLayout(const char *layoutClassName)
{
return instance()->doCreateLayout(QLatin1String(layoutClassName));
}
inline void Factory::registerAppender(const QString &appenderClassName,
AppenderFactoryFunc appenderFactoryFunc)
{
instance()->doRegisterAppender(appenderClassName, appenderFactoryFunc);
}
inline void Factory::registerAppender(const char *appenderClassName,
AppenderFactoryFunc appenderFactoryFunc)
{
instance()->doRegisterAppender(QLatin1String(appenderClassName), appenderFactoryFunc);
}
inline void Factory::registerFilter(const QString &filterClassName,
FilterFactoryFunc filterFactoryFunc)
{
instance()->doRegisterFilter(filterClassName, filterFactoryFunc);
}
inline void Factory::registerFilter(const char *filterClassName,
FilterFactoryFunc filterFactoryFunc)
{
instance()->doRegisterFilter(QLatin1String(filterClassName), filterFactoryFunc);
}
inline void Factory::registerLayout(const QString &filterClassName,
LayoutFactoryFunc layoutFactoryFunc)
{
instance()->doRegisterLayout(filterClassName, layoutFactoryFunc);
}
inline void Factory::registerLayout(const char *layoutClassName,
LayoutFactoryFunc layoutFactoryFunc)
{
instance()->doRegisterLayout(QLatin1String(layoutClassName), layoutFactoryFunc);
}
inline QStringList Factory::registeredAppenders()
{
QMutexLocker locker(&instance()->mObjectGuard);
return instance()->mAppenderRegistry.keys();
}
inline QStringList Factory::registeredFilters()
{
QMutexLocker locker(&instance()->mObjectGuard);
return instance()->mFilterRegistry.keys();
}
inline QStringList Factory::registeredLayouts()
{
QMutexLocker locker(&instance()->mObjectGuard);
return instance()->mLayoutRegistry.keys();
}
inline void Factory::setObjectProperty(QObject *object,
const QString &property,
const QString &value)
{
instance()->doSetObjectProperty(object, property, value);
}
inline void Factory::setObjectProperty(QObject *object,
const char *property,
const QString &value)
{
instance()->doSetObjectProperty(object, QLatin1String(property), value);
}
inline void Factory::unregisterAppender(const QString &appenderClassName)
{
instance()->doUnregisterAppender(appenderClassName);
}
inline void Factory::unregisterAppender(const char *appenderClassName)
{
instance()->doUnregisterAppender(QLatin1String(appenderClassName));
}
inline void Factory::unregisterFilter(const QString &filterClassName)
{
instance()->doUnregisterFilter(filterClassName);
}
inline void Factory::unregisterFilter(const char *filterClassName)
{
instance()->doUnregisterFilter(QLatin1String(filterClassName));
}
inline void Factory::unregisterLayout(const QString &filterClassName)
{
instance()->doUnregisterLayout(filterClassName);
}
inline void Factory::unregisterLayout(const char *layoutClassName)
{
instance()->doUnregisterLayout(QLatin1String(layoutClassName));
}
} // namespace Log4Qt
#endif // LOG4QT_HELPERS_FACTORY_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_HELPERS_INITIALISATIONHELPER_H
#define LOG4QT_HELPERS_INITIALISATIONHELPER_H
#include "log4qt/log4qtshared.h"
#include <QHash>
#include <QString>
class QMutex;
namespace Log4Qt
{
/*!
* LOG4QT_IMPLEMENT_INSTANCE implements an instance function for a
* singleton class \a TYPE.
*
*
* The following example illustrates how to use the macro to create a
* singleton class:
*
* \code
* #file: mysingleton.h
*
* class MySingleton
* {
* private:
* MySingleton();
* ~MySingleton();
* public:
* MySingleton *instance();
* }
* \endcode
* \code
* #file: mysingleton.cpp
*
* #include mysingleton.h
*
* MySingleton::MySingleton()
* {}
*
* MySingleton::~MySingleton()
* {}
*
* LOG4QT_IMPLEMENT_INSTANCE(MySingleton)
*
* \endcode
*
* \note The function created by the macro is thread-safe.
*
* \sa \ref Log4Qt::InitialisationHelper "InitialisationHelper"
*/
#define LOG4QT_IMPLEMENT_INSTANCE(TYPE) \
TYPE *TYPE::instance() \
{ \
static auto * singelton(new TYPE); \
return singelton; \
}
/*!
* \brief The class InitialisationHelper performs static initialisation
* tasks.
*
* The InitialisationHelper is either created on the first call or through
* static initialisation. It will capture the programs startup time,
* which can be retrieved using startTime(). The system environment
* is analysed for package related definitions. The result is available
* over environmentSettings(). The packages custom types are registered with
* the Qt type system.
*
* Settings for the package can be retrieved using setting(). Two macros
* are available to help with the creation of singletons / global static
* objects and \ref Log4Qt::LOG4QT_IMPLEMENT_INSTANCE "LOG4QT_IMPLEMENT_INSTANCE").
*
* \note All the functions declared in this class are thread-safe.
*
* \sa \ref Init "Initialization procedure",
*/
class LOG4QT_EXPORT InitialisationHelper
{
private:
InitialisationHelper();
virtual ~InitialisationHelper();
Q_DISABLE_COPY(InitialisationHelper)
public:
/*!
* Returns a hash with the settings retrieved from the system
* environment on startup.
*
* The following table shows the environment variables taken into
* account and the setting key used for them.
*
* <table align="center" border="1" cellpadding="2" cellspacing="0" bordercolor="#84b0c7">
* <tr bgcolor="#d5e1e8">
* <th width="25%"> Environment variable </th>
* <th width="25%"> Setting key </th>
* </tr><tr>
* <td> LOG4QT_DEBUG </td>
* <td> Debug </td>
* </tr><tr bgcolor="#ffffff">
* <td> LOG4QT_DEFAULTINITOVERRIDE </td>
* <td> DefaultInitOverride </td>
* </tr><tr>
* <td> LOG4QT_CONFIGURATION </td>
* <td> Configuration </td>
* </tr>
* </table>
*
* \sa \ref Env "Environment Variables",
* setting()
*/
static QHash<QString, QString> environmentSettings();
/*!
* Returns the InitialisationHelper instance.
*/
static InitialisationHelper *instance();
/*!
* Returns the value for the setting \a rKey or \a rDefault, if it is
* not defined.
*
* A setting can be either defined by an environment variable or by a
* key in the application setting. The function will first test the
* settings made by environment variables for the key \a rKey using
* environmentSettings(). If the key is not present and a
* QCoreApplication exists, the application settings are tested for
* the key \a rKey in the group \c %Log4Qt.
*
* The following setting exists:
*
* <table align="center" border="1" cellpadding="2" cellspacing="0" bordercolor="#84b0c7">
* <tr bgcolor="#d5e1e8">
* <th width="25%"> Setting key </th>
* <th> Description </th>
* </tr><tr>
* <td> Debug </td>
* <td> The variable controls the Level value for the logger
* LogManager::logLogger(). If the value is a valid Level string,
* the level for the logger is set to the level. If the value is not
* a valid Level string, \ref Level::DEBUG_INT "DEBUG_INT" is used.
* Otherwise \ref Level::ERROR_INT "ERROR_INT" is used. </td>
* </tr><tr bgcolor="#ffffff">
* <td> DefaultInitOverride </td>
* <td> The variable controls the \ref Init "initialization procedure"
* performed by the \ref LogManager "LogManager" on startup.
* If it is set to any other value then \c false the \ref Init
* "initialization procedure" is skipped.</td>
* </tr><tr>
* <td> Configuration </td>
* <td> Specifies the configuration file used for initialising the package.</td>
* </tr><tr bgcolor="#ffffff">
* <td> ConfiguratorClass </td>
* <td> Specifies the configurator class used for initialising the package.</td>
* </tr>
* </table>
*
* \sa environmentSettings(), \ref Env "Environment Variables",
* \ref Init "Initialization procedure",
* LogManager::configureLogLogger(), LogManager::startup()
*/
static QString setting(const QString &key,
const QString &defaultValue = QString());
/*!
* Returns the start time of the program as the number of milliseconds
* that have passed since 1970-01-01T00:00:00,000, Coordinated
* Universal Time (Qt::UTC).
*
* \sa DateTime::fromMilliSeconds(),
* DateTime::toMilliSeconds()
*/
static qint64 startTime();
private:
void doInitialiseEnvironmentSettings();
void doRegisterTypes();
QString doSetting(const QString &key,
const QString &defaultValue) const;
static bool shutdown();
static bool staticInitialisation();
private:
const qint64 mStartTime;
QHash <QString, QString> mEnvironmentSettings;
static bool mStaticInitialisation;
};
inline QHash<QString, QString> InitialisationHelper::environmentSettings()
{
return instance()->mEnvironmentSettings;
}
inline QString InitialisationHelper::setting(const QString &key,
const QString &defaultValue)
{
return instance()->doSetting(key, defaultValue);
}
inline qint64 InitialisationHelper::startTime()
{
return instance()->mStartTime;
}
} // namespace Log4Qt
#endif // LOG4QT_HELPERS_INITIALISATIONHELPER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LOGERROR_H
#define LOG4QT_LOGERROR_H
#include "log4qt/log4qtshared.h"
#include <QString>
#include <QVariant>
namespace Log4Qt
{
/*!
* Creates an LogError object with the error message \a message, the error
* code \a code and the context \a context. The symbol of the error is
* set to \a code as string value.
*
* The following example logs an error, if a character is not a digit.
*
* \code
* if (!c.isDigit())
* {
* Error e = LOG4QT_ERROR(QT_TR_NOOP("Found character '%1' where digit was expected."),
* LAYOUT_EXPECTED_DIGIT_ERROR,
* "Log4Qt::PatternFormatter");
* e << QString(c);
* logger()->error(e);
* }
* \endcode
*/
#define LOG4QT_ERROR(message, code, context) \
LogError(message, code, #code, context)
/*!
* Creates an LogError object with the error message \a message and the
* error code \a code. The symbol of the error is set to \a code as string
* value. The context is set to the class name of the current object. The
* current objects class must be derived from QObject.
*
* The following example handles an error while opening a file.
*
* \code
* if (!mpFile->open(mode))
* {
* LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to open file '%1' for appender '%2'"),
* APPENDER_OPENING_FILE_ERROR);
* e << mFileName << name();
* e.addCausingError(LogError(mpFile->errorString(), mpFile->error()));
* logger()->error(e);
* return;
* }
* \endcode
*/
#define LOG4QT_QCLASS_ERROR(message, code) \
LogError(message, code, #code, this->metaObject()->className())
/*!
* \brief The class LogError represents an error.
*
* The class error allows storing error information in a structured way.
* The error message is stored separately from the information that may be
* substituted into the message string. This way it is possible to access
* all information after the error has been raised. It also allows to
* translate the error at a later point in time or to get a translated and
* a not translated error text (e.g. translated for the UI and not
* translated for a log).
*
* The message is accessed using message() and setMessage(). Arguments for
* the message can be added using addArg() or operator<<(). The arguments
* can be retrieved using args(). The message with substituted arguments
* is returned by messageWithArgs().
*
* An error code can be set as integer value code() and/or a symbolic value
* symbol().
*
* To allow the translation of the message the error stores the translation
* context (context(), setContext()). The translated message can be accessed
* using translatedMessage() or using translatedMessageWithArgs(), if it
* should contain the arguments.
*
* An error can have one or more related errors that caused it. An error is
* related using addCausingError(). All causing errors can be retrieved using
* causingErrors().
*
* A per thread error can be maintained using lastError() and setLastError().
*
* There are two macros avaiable to simplify the error creation. The macro
* \ref Log4Qt::LOG4QT_ERROR "LOG4QT_ERROR" is used with classes not derived
* from QObject. The macro \ref Log4Qt::LOG4QT_QCLASS_ERROR "LOG4QT_QCLASS_ERROR"
* is used with classes derived from QObject.
*/
class LOG4QT_EXPORT LogError
{
public:
/*!
* The enum Encoding defines the 8-bit encoding of a character string
* arguments to \ref LogError::LogError(const char *, int, const char *,
* const char *, Encoding) "LogError::LogError()".
*
* \sa \ref LogError::LogError(const char *, int, const char *, const char *, Encoding) "LogError::LogError()"
*/
enum Encoding
{
/*! LATIN-1 */
LATIN1,
/*!
* The encoding specified by QTextCodec::codecForTr()
* (Latin-1 if none has been set).
*/
CODECFORTR,
/*! UTF-8 */
UNICODEUTF8
};
/*!
* Creates an empty error. The error code is set to 0 and all other
* members are set to be empty.
*
* \sa isEmpty()
*/
LogError();
/*!
* Creates an error with the Message \a message and the error code
* \a code. The symbol for the error code is set to \a rSymbol and the
* context to \a rContext.
*
* \a rContext must be string that can be converted to Latin-1. The
* Latin-1 representation of the string is used with
* QApplication::translate(), if a translation for \a message is
* requested.
*
* \sa translatedMessage(), translatedMessageWithArgs()
*/
explicit LogError(const QString &message,
int code = 0,
const QString &symbol = QString(),
const QString &context = QString());
/*!
* Creates an error with the Message \a pMessage and the error code
* \a code. The symbol for the error code is set to \a pSymbol and the
* context to \a pContext.
*
* \a encoding specifies the encoding of \a pMessage. \a pSymbol and
* \a pContext are expected to be Latin-1.
*
* \note To support the macros \ref Log4Qt::LOG4QT_ERROR "LOG4QT_ERROR"
* and \ref Log4Qt::LOG4QT_QCLASS_ERROR "LOG4QT_QCLASS_ERROR"
* the function tests, if \a pSymbol is the string representation of
* \a code. If it is, the symbol is set to be empty. Otherwise symbol
* is set to \a pSymbol.
*
* \sa translatedMessage(), translatedMessageWithArgs()
*/
explicit LogError(const char *message,
int code = 0,
const char *symbol = nullptr,
const char *context = nullptr,
Encoding encoding = LATIN1);
/*!
* Returns the error code.
*
* \sa setCode()
*/
int code() const;
/*!
* Returns the context for the error.
*
* \sa setContext()
*/
QString context() const;
/*!
* Returns the error message.
*
* \sa setMessage()
*/
QString message() const;
/*!
* Returns the symbol for the error code.
*
* \sa setSymbol()
*/
QString symbol() const;
/*!
* Returns the translated error message.
*
* The translated message is created by calling
* QCoreApplication::translate() using context().toLatin1() as
* context and message.toUtf8() as message.
*
* \sa translatedMessageWithArgs()
*/
QString translatedMessage() const;
/*!
* Sets the error code to \a code.
*
* \sa code()
*/
void setCode(int code);
/*!
* Sets the context to \a className.
*
* \a rContext must be string that can be converted to Latin-1. The
* Latin-1 representation of the string is used with
* QApplication::translate(), if a translation for \a message is
* requestd.
*
* \sa context(), translatedMessage(), translatedMessageWithArgs()
*/
void setContext(const QString &className);
/*!
* Sets the error message to \a message
*
* \sa message()
*/
void setMessage(const QString &message);
/*!
* Sets the symbol for the error code to \a symbol.
*
* \sa symbol()
*/
void setSymbol(const QString &symbol);
/*!
* Returns the last error set for the current thread using
* setLastError().
*
* \note: This function is thread-safe.
*
* \sa setLastError()
*/
static LogError lastError();
/*!
* Sets the last error for the current thread to \a logError.
*
* \note: This function is thread-safe.
*
* \sa lastError()
*/
static void setLastError(const LogError &logError);
/*!
* Appends \a rArg to the list of arguments and returns a reference to
* this error.
*
* \sa operator<<(), args(), clearArgs()
*/
LogError &addArg(const QVariant &arg);
/*!
* This is an overloaded member function, provided for convenience.
*/
LogError &addArg(int arg);
/*!
* This is an overloaded member function, provided for convenience.
*/
LogError &addArg(const QString &arg);
/*!
* Appends \a logError to the list of causing errors and returns a
* reference to this error.
*
* \sa causingErrors(), clearCausingErrors()
*/
LogError &addCausingError(const LogError &logError);
/*!
* Returns the list of arguments that have been added to this error.
*
* \sa addArg(), operator<<(), clearArgs()
*/
QList<QVariant> args() const;
/*!
* Returns the list of causing errors that have been added to this error.
*
* \sa addArg(), operator<<(), clearArgs()
*/
QList<LogError> causingErrors() const;
/*!
* Clears the list of arguments that have been added to this error.
*
* \sa addArg(), operator<<(), args()
*/
void clearArgs();
/*!
* Clears the list of causing errors that have been added to this error.
*
* \sa addCausingError(), causingErrors()
*/
void clearCausingErrors();
/*!
* Returns true, if the error code is 0 and the message is empty.
* Otherwise it returns false.
*
* \sa code(), message()
*/
bool isEmpty() const;
/*!
* Returns the message with arguments. The arguments are incoorporated
* into the messag using QString::arg().
*
* \sa QString::arg(), translatedMessageWithArgs()
*/
QString messageWithArgs() const;
/*!
* Returns the translated message with arguments. The arguments are
* incoorporated into the messag using QString::arg().
*
* \sa QString::arg(), messageWithArgs(), translatedMessage()
*/
QString translatedMessageWithArgs() const;
/*!
* Appends \a rArg to the list of arguments and returns a reference to
* this error.
*
* \sa addArg()
*/
LogError &operator<<(const QVariant &arg);
/*!
* This is an overloaded member function, provided for convenience.
*/
LogError &operator<<(int arg);
/*!
* This is an overloaded member function, provided for convenience.
*/
LogError &operator<<(const QString &arg);
/*!
* Returns a string representation of the error.
*
* The string has the following format:
*
* <tt>
* message (context::symbol, code): causing_error, causing_error
* </tt>
*
* If members are empty they are omitted:
* - Omit context, if empty
* - Omit symbol, if empty
* - Omit double colon with context and symbol, if both are empty
* - Omit code, if 0
* - Omit bracket with context/symbol and code, if all are empty
* - Omit colon with causing errors, if no causing errors exist
*/
QString toString() const;
private:
QString insertArgs(const QString &message) const;
QString cleanMessage(const QString &message);
private:
int mCode;
QString mContext;
QString mMessage;
QString mSymbol;
QList<QVariant> mArgs;
QList<LogError> mCausingErrors;
#ifndef QT_NO_DATASTREAM
// Needs to be friend to stream objects
friend QDataStream &operator<<(QDataStream &stream,
const LogError &logError);
friend QDataStream &operator>>(QDataStream &stream,
LogError &logError);
#endif // QT_NO_DATASTREAM
};
#ifndef QT_NO_DATASTREAM
/*!
* \relates LogError
*
* Writes the given error \a logError to the given stream \a rStream,
* and returns a reference to the stream.
*/
QDataStream &operator<<(QDataStream &stream,
const LogError &logError);
/*!
* \relates LogError
*
* Reads an error from the given stream \a rStream into the given
* error \a logError, and returns a reference to the stream.
*/
QDataStream &operator>>(QDataStream &stream,
LogError &logError);
#endif // QT_NO_DATASTREAM
inline int LogError::code() const
{
return mCode;
}
inline QString LogError::context() const
{
return mContext;
}
inline QString LogError::message() const
{
return mMessage;
}
inline QString LogError::symbol() const
{
return mSymbol;
}
inline void LogError::setCode(int code)
{
mCode = code;
}
inline void LogError::setContext(const QString &context)
{
mContext = context;
}
inline void LogError::setMessage(const QString &message)
{
mMessage = cleanMessage(message);
}
inline void LogError::setSymbol(const QString &symbol)
{
mSymbol = symbol;
}
inline LogError &LogError::addArg(const QVariant &arg)
{
mArgs << arg;
return *this;
}
inline LogError &LogError::addArg(int arg)
{
mArgs << QVariant(arg);
return *this;
}
inline LogError &LogError::addArg(const QString &arg)
{
mArgs << QVariant(arg);
return *this;
}
inline LogError &LogError::addCausingError(const LogError &logError)
{
mCausingErrors << logError;
return *this;
}
inline QList<QVariant> LogError::args() const
{
return mArgs;
}
inline void LogError::clearArgs()
{
mArgs.clear();
}
inline void LogError::clearCausingErrors()
{
mCausingErrors.clear();
}
inline QList<LogError> LogError::causingErrors() const
{
return mCausingErrors;
}
inline bool LogError::isEmpty() const
{
return mCode || !mMessage.isEmpty();
}
inline QString LogError::messageWithArgs() const
{
return insertArgs(message());
}
inline QString LogError::translatedMessageWithArgs() const
{
return insertArgs(translatedMessage());
}
inline LogError &LogError::operator<<(const QVariant &arg)
{
return addArg(arg);
}
inline LogError &LogError::operator<<(int arg)
{
return addArg(arg);
}
inline LogError &LogError::operator<<(const QString &arg)
{
return addArg(arg);
}
} // namespace Log4Qt
Q_DECLARE_METATYPE(Log4Qt::LogError)
Q_DECLARE_TYPEINFO(Log4Qt::LogError, Q_MOVABLE_TYPE);
#endif // LOG4QT_ERROR_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_OPTIONCONVERTER_H
#define LOG4QT_OPTIONCONVERTER_H
#include "log4qt/log4qtshared.h"
#include "log4qt/level.h"
#include <QString>
namespace Log4Qt
{
class Properties;
/*!
* \brief The class OptionConverter provides functions to convert strings
* to property values.
*/
class LOG4QT_EXPORT OptionConverter
{
private:
OptionConverter();
Q_DISABLE_COPY(OptionConverter)
public:
static QString findAndSubst(const Properties &properties,
const QString &key);
/*!
* Returns the JAVA class name \a className as C++ class name by
* replacing all . characters with ::.
*/
static QString classNameJavaToCpp(const QString &className);
/*!
* Converts the option \a option to a boolean value. Valid strings
* for true are "true", "enabled" and "1". Valid strings
* for false are "false", "disabled" and "0". If the conversion is
* successful, the target is returned and \a ok is set to true.
* Otherwise an error is written to the log, \a ok is set to false
* and false is returned.
*/
static bool toBoolean(const QString &option,
bool *ok = nullptr);
static bool toBoolean(const QString &option,
bool defaultValue);
/*!
* Converts the option string \a option to a file size. The string can
* be a positive integer followed by an optional unit suffix "KB", "MB"
* or "GB". If a unit suffix is specified the the integer is
* interpreted as kilobytes, megabytes or gigabytes. If the conversion
* is successful, the size is returned and \a ok is set to true.
* Otherwise an error is written to the log, \a ok is set to false
* and 0 is returned.
*/
static qint64 toFileSize(const QString &option,
bool *ok = nullptr);
/*!
* Converts the option \a option to a integer value using
* QString::toInt(). If the conversion is successful, the integer is
* returned and \a ok is set to true. Otherwise an error is written
* to the log, \a ok is set to false and 0 is returned.
*/
static int toInt(const QString &option,
bool *ok = nullptr);
/*!
* Converts the option \a option to a level value using
* Level::fromString(). If the conversion is successful, the level
* is returned and \a ok is set to true. Otherwise an error is
* written to the log, \a ok is set to false and a level with
* the value Level::NULL_INT is returned.
*
* \sa Level::fromString()
*/
static Level toLevel(const QString &option,
bool *ok = nullptr);
static Level toLevel(const QString &option,
Log4Qt::Level defaultValue);
/*!
* Converts the option \a option to a ConsoleAppender::Target value.
* Valid strings for \a option are "System.out", "STDOUT_TARGET",
* "System.err" and "STDERR_TARGET". If the conversion is successful,
* the target is returned and \a ok is set to true. Otherwise an
* error is written to the log, \a ok is set to false and
* ConsoleAppender::STDOUT_TARGET is returned.
*/
static int toTarget(const QString &option,
bool *ok = nullptr);
};
} // namespace Log4Qt
Q_DECLARE_TYPEINFO(Log4Qt::OptionConverter, Q_MOVABLE_TYPE);
#endif // LOG4QT_OPTIONCONVERTER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_PATTERNFORMATTER_H
#define LOG4QT_PATTERNFORMATTER_H
#include "log4qt/log4qtshared.h"
#include <QList>
#include <QString>
namespace Log4Qt
{
class FormattingInfo;
class PatternConverter;
class LoggingEvent;
/*!
* \brief The class PatternFormatter formats a logging event based on a
* pattern string.
*
* The class PatternFormatter formats a LoggingEvent base on a pattern
* string. It is used by the patternLayout and TTCCLayout class to
* implement the formatting.
*
* On object construction the provided patterns tring is parsed. Based on
* the information found a chain of PatternConverter is created. Each
* PatternConverter handles a certain member of a LoggingEvent.
*
* \sa PatternLayout::format()
* \sa TTCCLayout::format()
*/
class LOG4QT_EXPORT PatternFormatter
{
public:
/*!
* Creates a PatternFormatter using a the specified \a pattern.
*/
PatternFormatter(const QString &pattern);
/*!
* Destroys the PatternFormatter and all PatternConverter.
*/
virtual ~PatternFormatter();
private:
Q_DISABLE_COPY(PatternFormatter)
public:
/*!
* Formats the given \a loggingEvent using the chain of
* PatternConverter created during construction from the specified
* pattern.
*/
QString format(const LoggingEvent &loggingEvent) const;
private:
/*!
* If the character \a digit is a digit the digit is added to the
* integer \a value and the function returns true. Otherwise the
* function returns false.
*
* The function adds the digit by multiplying the existing value
* with ten and adding the numerical value of the digit. If the
* maximum integer value would be exceeded by the operation
* \a value is set to INT_MAX.
*/
bool addDigit(QChar digit,
int &value);
/*!
* Creates a PatternConverter based on the specified conversion
* character \a rChar, the formatting information
* \a formattingInfo and the option \a option.
*
* The PatternConverter converter is appended to the list of
* PatternConverters.
*/
void createConverter(QChar character,
Log4Qt::FormattingInfo formattingInfo,
const QString &option = QString());
/*!
* Creates a LiteralPatternConverter with the string literal
* \a literal.
*
* The PatternConverter converter is appended to the list of
* PatternConverters.
*/
void createLiteralConverter(const QString &literal);
/*!
* Parses the pattern string specified on construction and creates
* PatternConverter according to it.
*/
void parse();
/*!
* Parses an integer option from an option string. If the string is
* not a valid integer or the integer value is less then zero, zero
* is returned. Returns the end of line seperator for the operating
* system.
*/
int parseIntegeoption(const QString &option);
private:
const QString mIgnoreCharacters;
const QString mConversionCharacters;
const QString mOptionCharacters;
QString mPattern;
QList<PatternConverter *> mPatternConverters;
};
} // namespace Log4Qt
Q_DECLARE_TYPEINFO(Log4Qt::PatternFormatter, Q_MOVABLE_TYPE);
#endif // LOG4QT_PATTERNFORMATTER_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_PROPERTIES_H
#define LOG4QT_PROPERTIES_H
#include "log4qt/log4qtshared.h"
#include <QHash>
#include <QStringList>
class QIODevice;
class QSettings;
namespace Log4Qt
{
/*!
* \brief The class Properties implements a JAVA property hash.
*/
class LOG4QT_EXPORT Properties : public QHash<QString, QString>
{
public:
Properties(Properties *pDefaultProperties = nullptr);
public:
Properties *defaultProperties() const;
QString property(const QString &key) const;
QString property(const QString &key,
const QString &defaultValue) const;
void setDefaultProperties(Properties *defaultProperties);
void setProperty(const QString &key,
const QString &value);
void load(QIODevice *pDevice);
/*!
* Reads all child keys from the QSettings object \a settings and
* inserts them into this object. The value is created using
* QVariant::toString(). Types that do not support toString() are
* resulting in an empty string.
*
* \code
* QSettings settings;
* settings.setValue("Package", "Full");
* settings.setValue("Background", Qt::white);
* settings.setValue("Support", true);
* settings.setValue("Help/Language", "en_UK");
*
* Properties properties
* properties.load(&settings)
*
* // properties (("Package", "Full"), ("Background", ""), ("Support", "true"))
* \endcode
*/
void load(const QSettings &settings);
QStringList propertyNames() const;
private:
void parseProperty(const QString &property,
int line);
static int hexDigitValue(QChar digit);
static QString trimLeft(const QString &line);
private:
Properties *mpDefaultProperties;
static const char msEscapeChar;
static const char *msValueEscapeCodes;
static const char *msValueEscapeChars;
static const char *msKeyEscapeCodes;
static const char *msKeyEscapeChars;
};
inline Properties::Properties(Properties *pDefaultProperties) :
mpDefaultProperties(pDefaultProperties)
{}
inline Properties *Properties::defaultProperties() const
{
return mpDefaultProperties;
}
inline void Properties::setDefaultProperties(Properties *defaultProperties)
{
mpDefaultProperties = defaultProperties;
}
inline void Properties::setProperty(const QString &key,
const QString &value)
{
insert(key, value);
}
} // namespace Log4Qt
Q_DECLARE_TYPEINFO(Log4Qt::Properties, Q_MOVABLE_TYPE);
#endif // LOG4QT_PROPERTIES_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_HIERARCHY_H
#define LOG4QT_HIERARCHY_H
#include "loggerrepository.h"
#include <QHash>
#include <QReadWriteLock>
namespace Log4Qt
{
/*!
* \brief The class Hierarchy implements a logger repository.
*
* \note All the functions declared in this class are thread-safe.
*/
class LOG4QT_EXPORT Hierarchy : public LoggerRepository
{
public:
Hierarchy();
~Hierarchy() override;
public:
bool exists(const QString &name) const override;
Logger *logger(const QString &name) override;
QList<Logger *> loggers() const override;
Logger *rootLogger() const override;
Level threshold() const override;
void setThreshold(Level level) override;
void setThreshold(const QString &threshold) override;
bool isDisabled(Level level) override;
void resetConfiguration() override;
void shutdown() override;
private:
Logger *createLogger(const QString &name);
void resetLogger(Logger *logger, Level level) const;
private:
mutable QReadWriteLock mObjectGuard;
QHash<QString, Logger *> mLoggers;
Level mThreshold;
Logger *mRootLogger;
};
inline Logger *Hierarchy::rootLogger() const
{
return mRootLogger;
}
inline Level Hierarchy::threshold() const
{
return mThreshold;
}
inline void Hierarchy::setThreshold(Level level)
{
mThreshold = level;
}
inline bool Hierarchy::isDisabled(Level level)
{
return level < mThreshold;
}
} // namespace Log4Qt
#endif // LOG4QT_HIERARCHY_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LAYOUT_H
#define LOG4QT_LAYOUT_H
#include "log4qt.h"
#include "log4qtsharedptr.h"
#include <QObject>
namespace Log4Qt
{
class LoggingEvent;
/*!
* \brief The class Layout is the base class for all layouts.
*
* \note The ownership and lifetime of objects of this class are managed. See
* \ref Ownership "Object ownership" for more details.
*/
class LOG4QT_EXPORT Layout : public QObject
{
Q_OBJECT
/*!
* The property holds the content type of the layout.
*
* \sa contentType()
*/
Q_PROPERTY(QString footercontentType READ contentType)
/*!
* The property holds the footer used by the layout.
*
* \sa footer(), setFooter()
*/
Q_PROPERTY(QString footer READ footer WRITE setFooter)
/*!
* The property holds the header used by the layout.
*
* \sa header(), setHeader()
*/
Q_PROPERTY(QString header READ header WRITE setHeader)
public:
Layout(QObject *parent = nullptr);
virtual ~Layout();
public:
virtual QString contentType() const;
QString footer() const;
QString header() const;
QString name() const;
void setFooter(const QString &footer);
void setHeader(const QString &header);
void setName(const QString &name);
virtual void activateOptions();
virtual QString format(const LoggingEvent &event) = 0;
/*!
* Returns the end of line seperator for the operating system.
*
* Windows: \\r\\n
* Mac: \\r
* UNIX: \\n
*/
static QString endOfLine();
// Member variables
private:
Q_DISABLE_COPY(Layout)
QString mFooter;
QString mHeader;
};
inline QString Layout::footer() const
{
return mFooter;
}
inline QString Layout::header() const
{
return mHeader;
}
inline QString Layout::name() const
{
return objectName();
}
inline void Layout::setFooter(const QString &footer)
{
mFooter = footer;
}
inline void Layout::setHeader(const QString &header)
{
mHeader = header;
}
inline void Layout::setName(const QString &name)
{
setObjectName(name);
}
using LayoutSharedPtr = Log4QtSharedPtr<Layout>;
} // namespace Log4Qt
#endif // LOG4QT_LAYOUT_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LEVEL_H
#define LOG4QT_LEVEL_H
#include "log4qt.h"
#include <QString>
#include <QMetaType>
namespace Log4Qt
{
/*!
* \brief The class Level defines the level of a logging event.
*
* \note All the functions declared in this class are thread-safe.
*/
class LOG4QT_EXPORT Level
{
public:
// Comparisson operators rely on the order:
// NULL_INT < ALL_INT < TRACE_INT < ...
// Serialisation uses unsigned 8 bit int
/*!
* The enumeration Value contains all possible Level values.
*/
enum Value
{
/*! NULL_INT is used for no level has been specified */
NULL_INT = 0,
ALL_INT = 32,
TRACE_INT = 64,
DEBUG_INT = 96,
INFO_INT = 128,
WARN_INT = 150,
ERROR_INT = 182,
FATAL_INT = 214,
OFF_INT = 255
};
public:
Level(Value value = NULL_INT)
: mValue(value)
{
}
int syslogEquivalent() const;
int toInt() const
{
return mValue;
}
bool operator==(const Level other) const
{
return mValue == other.mValue;
}
bool operator!=(const Level other) const
{
return mValue != other.mValue;
}
bool operator<(const Level other) const
{
return mValue < other.mValue;
}
bool operator<=(const Level other) const
{
return mValue <= other.mValue;
}
bool operator>(const Level other) const
{
return mValue > other.mValue;
}
bool operator>=(const Level other) const
{
return mValue >= other.mValue;
}
QString toString() const;
static Level fromString(const QString &level, bool *ok = nullptr);
private:
volatile Value mValue;
#ifndef QT_NO_DATASTREAM
// Needs to be friend to stream objects
friend LOG4QT_EXPORT QDataStream &operator<<(QDataStream &out,
Log4Qt::Level level);
friend LOG4QT_EXPORT QDataStream &operator>>(QDataStream &in,
Level &level);
#endif // QT_NO_DATASTREAM
};
#ifndef QT_NO_DATASTREAM
/*!
* \relates Level
*
* Writes the given error \a rLevel to the given stream \a rStream,
* and returns a reference to the stream.
*/
LOG4QT_EXPORT QDataStream &operator<<(QDataStream &out,
Log4Qt::Level level);
/*!
* \relates Level
*
* Reads an error from the given stream \a rStream into the given
* error \a rLevel, and returns a reference to the stream.
*/
LOG4QT_EXPORT QDataStream &operator>>(QDataStream &in,
Level &level);
#endif // QT_NO_DATASTREAM
} // namespace Log4Qt
Q_DECLARE_METATYPE(Log4Qt::Level)
Q_DECLARE_TYPEINFO(Log4Qt::Level, Q_MOVABLE_TYPE);
#endif // LOG4QT_LEVEL_H
此差异已折叠。
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_SHARED_H
#define LOG4QT_SHARED_H
#include <QtGlobal>
// Define LOG4QT_STATIC in you applikation if you want to link against the
// static version of Log4Qt
#ifdef LOG4QT_STATIC
# define LOG4QT_EXPORT
#else
# if defined(LOG4QT_LIBRARY)
# define LOG4QT_EXPORT Q_DECL_EXPORT
# else
# define LOG4QT_EXPORT Q_DECL_IMPORT
# endif
#endif
#endif // LOG4QT_SHARED_H
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LOG4QTSHAREDPTR_H
#define LOG4QT_LOG4QTSHAREDPTR_H
#include <QSharedPointer>
#include <QObject>
#include <type_traits>
namespace Log4Qt
{
template<typename Log4QtClass>
class Log4QtSharedPtr : public QSharedPointer<Log4QtClass>
{
public:
Log4QtSharedPtr(Log4QtClass *ptr)
: QSharedPointer<Log4QtClass>(ptr, &Log4QtClass::deleteLater)
{
static_assert(std::is_base_of<QObject, Log4QtClass>::value, "Need a QObject derived class here");
}
Log4QtSharedPtr()
: QSharedPointer<Log4QtClass>()
{
}
Log4QtSharedPtr(const QSharedPointer<Log4QtClass> &other)
: QSharedPointer<Log4QtClass>(other)
{
}
Log4QtSharedPtr(const QWeakPointer<Log4QtClass> &other)
: QSharedPointer<Log4QtClass>(other)
{
}
};
}
#endif // LOG4QT_LOG4QTSHAREDPTR_H
此差异已折叠。
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LOGGERREPOSITORY_H
#define LOG4QT_LOGGERREPOSITORY_H
#include "level.h"
#include <QList>
namespace Log4Qt
{
class Logger;
/*!
* \brief The class LoggerRepository is abstract base class for a logger
* repository.
*/
class LOG4QT_EXPORT LoggerRepository
{
public:
LoggerRepository();
virtual ~LoggerRepository();
LoggerRepository(const LoggerRepository &other) = delete;
LoggerRepository &operator=(const LoggerRepository &other) = delete;
virtual bool exists(const QString &name) const = 0;
virtual Logger *logger(const QString &name) = 0;
virtual QList<Logger *> loggers() const = 0;
virtual Logger *rootLogger() const = 0;
virtual Level threshold() const = 0;
virtual void setThreshold(Level level) = 0;
virtual void setThreshold(const QString &threshold) = 0;
virtual bool isDisabled(Level level) = 0;
virtual void resetConfiguration() = 0;
virtual void shutdown() = 0;
};
} // namespace Log4Qt
#endif // LOG4QT_LOGGERREPOSITORY_H
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_XMLLAYOUT_H
#define LOG4QT_XMLLAYOUT_H
#include "layout.h"
namespace Log4Qt
{
class LOG4QT_EXPORT XMLLayout : public Layout
{
Q_OBJECT
public:
explicit XMLLayout(QObject *parent = nullptr);
QString format(const LoggingEvent &event) override;
private:
Q_DISABLE_COPY(XMLLayout)
};
}
#endif // LOG4QT_XMLLAYOUT_H
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册