parent
d3c6a77899
commit
a6387729d2
|
@ -0,0 +1,107 @@
|
||||||
|
.build/
|
||||||
|
_other/
|
||||||
|
_distrib*/
|
||||||
|
|
||||||
|
# Tmp files
|
||||||
|
*~
|
||||||
|
Thumbs.db*
|
||||||
|
|
||||||
|
# C++ objects and libs
|
||||||
|
*.slo
|
||||||
|
*.lo
|
||||||
|
*.o
|
||||||
|
*.a
|
||||||
|
*.la
|
||||||
|
*.lai
|
||||||
|
*.so
|
||||||
|
*.so.*
|
||||||
|
*.dll
|
||||||
|
*.dylib
|
||||||
|
*.ko
|
||||||
|
*.obj
|
||||||
|
*.elf
|
||||||
|
*.lib
|
||||||
|
|
||||||
|
# Qt-es
|
||||||
|
object_script.*.Release
|
||||||
|
object_script.*.Debug
|
||||||
|
*_plugin_import.cpp
|
||||||
|
/.qmake.cache
|
||||||
|
/.qmake.stash
|
||||||
|
*.pro.user
|
||||||
|
*.pro.user.*
|
||||||
|
*.qbs.user
|
||||||
|
*.qbs.user.*
|
||||||
|
*.moc
|
||||||
|
moc_*.cpp
|
||||||
|
moc_*.h
|
||||||
|
qrc_*.cpp
|
||||||
|
ui_*.h
|
||||||
|
*.qmlc
|
||||||
|
*.jsc
|
||||||
|
Makefile*
|
||||||
|
*build-*
|
||||||
|
*.qm
|
||||||
|
*.prl
|
||||||
|
|
||||||
|
# Qt unit tests
|
||||||
|
target_wrapper.*
|
||||||
|
|
||||||
|
# QtCreator
|
||||||
|
*.autosave
|
||||||
|
|
||||||
|
# QtCreator Qml
|
||||||
|
*.qmlproject.user
|
||||||
|
*.qmlproject.user.*
|
||||||
|
|
||||||
|
# QtCreator CMake
|
||||||
|
CMakeLists.txt.user*
|
||||||
|
|
||||||
|
# QtCreator 4.8< compilation database
|
||||||
|
compile_commands.json
|
||||||
|
|
||||||
|
# QtCreator local machine specific files for imported projects
|
||||||
|
*creator.user*
|
||||||
|
|
||||||
|
*_qmlcache.qrc
|
||||||
|
|
||||||
|
# ---> C
|
||||||
|
# Prerequisites
|
||||||
|
*.d
|
||||||
|
|
||||||
|
# Linker output
|
||||||
|
*.ilk
|
||||||
|
*.map
|
||||||
|
*.exp
|
||||||
|
|
||||||
|
# Precompiled Headers
|
||||||
|
*.gch
|
||||||
|
*.pch
|
||||||
|
|
||||||
|
# Executables
|
||||||
|
*.exe
|
||||||
|
*.out
|
||||||
|
*.app
|
||||||
|
*.i*86
|
||||||
|
*.x86_64
|
||||||
|
*.hex
|
||||||
|
|
||||||
|
# Debug files
|
||||||
|
*.dSYM/
|
||||||
|
*.su
|
||||||
|
*.idb
|
||||||
|
*.pdb
|
||||||
|
|
||||||
|
# Kernel Module Compile Results
|
||||||
|
*.mod*
|
||||||
|
*.cmd
|
||||||
|
.tmp_versions/
|
||||||
|
modules.order
|
||||||
|
Module.symvers
|
||||||
|
Mkfile.old
|
||||||
|
dkms.conf
|
||||||
|
|
||||||
|
# Fortran module files
|
||||||
|
*.mod
|
||||||
|
*.smod
|
||||||
|
|
|
@ -0,0 +1,10 @@
|
||||||
|
cmake_minimum_required(VERSION 4.0)
|
||||||
|
|
||||||
|
project (QtLoggerExample)
|
||||||
|
|
||||||
|
# Logger library:
|
||||||
|
add_subdirectory(lib_logger)
|
||||||
|
|
||||||
|
# Example Application:
|
||||||
|
add_subdirectory(application)
|
||||||
|
|
|
@ -0,0 +1,9 @@
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@ -0,0 +1,25 @@
|
||||||
|
MIT лицензия
|
||||||
|
|
||||||
|
Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
|
||||||
|
|
||||||
|
Данная лицензия разрешает лицам, получившим копию
|
||||||
|
данного программного обеспечения и сопутствующей документации
|
||||||
|
(в дальнейшем именуемыми «Программное Обеспечение»), безвозмездно
|
||||||
|
использовать Программное Обеспечение без ограничений,
|
||||||
|
включая неограниченное право на использование, копирование, изменение,
|
||||||
|
слияние, публикацию, распространение, сублицензирование и/или продажу
|
||||||
|
копий Программного Обеспечения, а также лицам, которым предоставляется
|
||||||
|
данное Программное Обеспечение, при соблюдении следующих условий:
|
||||||
|
|
||||||
|
Указанное выше уведомление об авторском праве и данные условия
|
||||||
|
должны быть включены во все копии или значимые части данного Программного Обеспечения.
|
||||||
|
|
||||||
|
ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ»,
|
||||||
|
БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ, ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ,
|
||||||
|
ВКЛЮЧАЯ ГАРАНТИИ ТОВАРНОЙ ПРИГОДНОСТИ, СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ
|
||||||
|
НАЗНАЧЕНИЮ И ОТСУТСТВИЯ НАРУШЕНИЙ, НО НЕ ОГРАНИЧИВАЯСЬ ИМИ.
|
||||||
|
НИ В КАКОМ СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ
|
||||||
|
ПО КАКИМ-ЛИБО ИСКАМ, ЗА УЩЕРБ ИЛИ ПО ИНЫМ ТРЕБОВАНИЯМ, В ТОМ ЧИСЛЕ,
|
||||||
|
ПРИ ДЕЙСТВИИ КОНТРАКТА, ДЕЛИКТЕ ИЛИ ИНОЙ СИТУАЦИИ,
|
||||||
|
ВОЗНИКШИМ ИЗ-ЗА ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
|
||||||
|
ИЛИ ИНЫХ ДЕЙСТВИЙ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ.
|
34
README.md
34
README.md
|
@ -1,3 +1,35 @@
|
||||||
# Qt_Logger_Example
|
# Qt_Logger_Example
|
||||||
|
|
||||||
Пример организации логирования в файл для Qt
|
Пример организации логирования в файл для Qt
|
||||||
|
|
||||||
|
## Библиотека lib_logger
|
||||||
|
|
||||||
|
Логгер представляет собой класс singleton и запускается на старте приложения, например в `main.cpp` через
|
||||||
|
|
||||||
|
```
|
||||||
|
Logger::instance().start();
|
||||||
|
```
|
||||||
|
|
||||||
|
После запуска используется стандартный механизм логирования Qt, никаких дополнительных действий не требуется.
|
||||||
|
Сохранение текста в файл выполняется в отдельном потоке. При этом механизм логирования полностью потокобезопасен.
|
||||||
|
|
||||||
|
Работает под Qt5, Qt6, ОС Windows и GNU/Linux.
|
||||||
|
|
||||||
|
## Приложение
|
||||||
|
|
||||||
|
Приложение использует библиотеку `lib_logger` для сохранения лога в файл. Логирование событий осуществляется через стандартный механизм Qt:
|
||||||
|
|
||||||
|
```
|
||||||
|
qInfo() << "Строка информации";
|
||||||
|
qDebug() << "Строка отладки";
|
||||||
|
qWarning() << "Строка предупреждения";
|
||||||
|
qCritical() << "Строка ошибки";
|
||||||
|
```
|
||||||
|
|
||||||
|
Строки отладки (`qDebug`, `qCDebug`) сохраняются только если приложение запущено с параметром `/debug` или в каталоге ПО находится файл `debug` (без расширения с любым содержанием).
|
||||||
|
Логи сохраняются в каталоге профиля приложения. Если в каталоге ПО находится файл `portable` (без расширения с любым содержанием), то каталог логов будет создан в подкаталоге `profile` каталога ПО.
|
||||||
|
|
||||||
|
## Внешний вид приложения для тестирования (Qt6, ОС Windows 11)
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,28 @@
|
||||||
|
|
||||||
|
# Файл для подключения в основной проект через include
|
||||||
|
# Настройки для приложений
|
||||||
|
|
||||||
|
include(${CMAKE_CURRENT_LIST_DIR}/common.cmake)
|
||||||
|
include(${CMAKE_CURRENT_LIST_DIR}/developer.cmake)
|
||||||
|
include(${CMAKE_CURRENT_LIST_DIR}/version.cmake)
|
||||||
|
|
||||||
|
# Имя выходного файла совпадает с названием проекта:
|
||||||
|
set(RUNTIME_OUTPUT_NAME ${PROJECT_NAME})
|
||||||
|
|
||||||
|
configure_file(
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/config.h.in
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/config.h
|
||||||
|
@ONLY
|
||||||
|
)
|
||||||
|
|
||||||
|
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${DISTRIB_DIR})
|
||||||
|
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${DISTRIB_DIR})
|
||||||
|
|
||||||
|
if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
|
||||||
|
configure_file(
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/versioninfo.rc.in
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/versioninfo.rc
|
||||||
|
@ONLY
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
|
@ -0,0 +1,52 @@
|
||||||
|
|
||||||
|
# Общие настройки для всех типов проектов
|
||||||
|
|
||||||
|
set(CMAKE_INCLUDE_CURRENT_DIR ON)
|
||||||
|
set(CMAKE_AUTOUIC ON)
|
||||||
|
set(CMAKE_AUTOMOC ON)
|
||||||
|
set(CMAKE_AUTORCC ON)
|
||||||
|
|
||||||
|
if (CMAKE_COMPILER_IS_GNUCXX)
|
||||||
|
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "9.0.0")
|
||||||
|
set(CMAKE_CXX_STANDARD 20)
|
||||||
|
else()
|
||||||
|
set(CMAKE_CXX_STANDARD 23)
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
set(CMAKE_CXX_STANDARD 23)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
|
|
||||||
|
# Поиск библиотек Qt:
|
||||||
|
find_package(QT NAMES Qt6 Qt5 REQUIRED)
|
||||||
|
|
||||||
|
# Настройки каталогов:
|
||||||
|
include(${CMAKE_CURRENT_LIST_DIR}/setup_directories.cmake)
|
||||||
|
|
||||||
|
# Определение разрядности:
|
||||||
|
if (${CMAKE_SIZEOF_VOID_P} STREQUAL 4)
|
||||||
|
set(DIR_PREFIX "32")
|
||||||
|
elseif (${CMAKE_SIZEOF_VOID_P} STREQUAL 8)
|
||||||
|
set(DIR_PREFIX "64")
|
||||||
|
endif ()
|
||||||
|
|
||||||
|
# Каталог для готовых приложений и библиотек после компиляции:
|
||||||
|
set(DISTRIB_DIR
|
||||||
|
${ROOT_PROJECT_DIR}_distrib/${CMAKE_SYSTEM_NAME}_Qt${QT_VERSION}_${DIR_PREFIX}-bit
|
||||||
|
)
|
||||||
|
|
||||||
|
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||||
|
set(IS_DEBUG TRUE)
|
||||||
|
set(IS_RELEASE FALSE)
|
||||||
|
else()
|
||||||
|
set(IS_DEBUG FALSE)
|
||||||
|
set(IS_RELEASE TRUE)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
message(STATUS "Project '${PROJECT_NAME}' compiler ${CMAKE_CXX_COMPILER} version: ${CMAKE_CXX_COMPILER_VERSION}")
|
||||||
|
message(STATUS "Project '${PROJECT_NAME}' distrib dir: '${DISTRIB_DIR}'")
|
||||||
|
message(STATUS "Project '${PROJECT_NAME}' IS_RELEASE: ${IS_RELEASE}, IS_DEBUG: ${IS_DEBUG}")
|
||||||
|
message(STATUS "Project '${PROJECT_NAME}' CMAKE_PREFIX_PATH: '${CMAKE_PREFIX_PATH}'")
|
||||||
|
message(STATUS "Project '${PROJECT_NAME}' CMAKE_SYSTEM_LIBRARY_PATH: '${CMAKE_SYSTEM_LIBRARY_PATH}'")
|
||||||
|
|
|
@ -0,0 +1,9 @@
|
||||||
|
#define PROG_NAME "@PROJECT_NAME@"
|
||||||
|
#define PROG_VERSION "@PROJECT_VERSION_MAJOR@.@PROJECT_VERSION_MINOR@.@PROJECT_VERSION_PATCH@.@BUILD_NUM@@PROJECT_VERSION_TWEAK@"
|
||||||
|
#define PROG_CAPTION "@PROJECT_NAME@ v"
|
||||||
|
#define PROG_DESCRIPTION "@PROJECT_DESCRIPTION@"
|
||||||
|
#define SOFT_DEVELOPER "@SOFT_DEVELOPER@"
|
||||||
|
#define DEVELOPER_DOMAIN "@DEVELOPER_DOMAIN@"
|
||||||
|
#define BUILD_DATE "@BUILD_DATE@"
|
||||||
|
#define BUILD_NUM "@BUILD_NUM@"
|
||||||
|
#define ORIGINAL_FILE_NAME "@ORIGINAL_FILE_NAME@"
|
|
@ -0,0 +1,289 @@
|
||||||
|
|
||||||
|
# Определение зависимостей после сборки приложения
|
||||||
|
|
||||||
|
cmake_minimum_required(VERSION 4.0)
|
||||||
|
|
||||||
|
set(LIBS_FIND_DIRS "${PREFIX}")
|
||||||
|
set(QT_SHARE_DIR "${PREFIX}")
|
||||||
|
|
||||||
|
if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
|
||||||
|
|
||||||
|
if (EXISTS "${PREFIX}/bin")
|
||||||
|
set(LIBS_FIND_DIRS "${PREFIX}/bin")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
else()
|
||||||
|
|
||||||
|
if (EXISTS "${PREFIX}/lib")
|
||||||
|
set(LIBS_FIND_DIRS "${PREFIX}/lib")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (EXISTS "${PREFIX}/share/qt${QT_VERSION_MAJOR}")
|
||||||
|
set(QT_SHARE_DIR "${PREFIX}/share/qt${QT_VERSION_MAJOR}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(TARGET_TYPE STREQUAL "EXECUTABLE")
|
||||||
|
|
||||||
|
if (EXISTS "${OUTPUT_DIR}/${TARGET_NAME}")
|
||||||
|
set(TARGET_FILE "${OUTPUT_DIR}/${TARGET_NAME}")
|
||||||
|
elseif (EXISTS "${OUTPUT_DIR}/${TARGET_NAME}.exe")
|
||||||
|
set(TARGET_FILE "${OUTPUT_DIR}/${TARGET_NAME}.exe")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
else()
|
||||||
|
|
||||||
|
if (EXISTS "${OUTPUT_DIR}/${TARGET_NAME}")
|
||||||
|
set(TARGET_FILE "${OUTPUT_DIR}/${TARGET_NAME}")
|
||||||
|
elseif (EXISTS "${OUTPUT_DIR}/${TARGET_NAME}.dll")
|
||||||
|
set(TARGET_FILE "${OUTPUT_DIR}/${TARGET_NAME}.dll")
|
||||||
|
elseif (EXISTS "${OUTPUT_DIR}/${TARGET_NAME}.so")
|
||||||
|
set(TARGET_FILE "${OUTPUT_DIR}/${TARGET_NAME}.so")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
endif()
|
||||||
|
|
||||||
|
message(STATUS "TARGET_FILE: '${TARGET_FILE}'")
|
||||||
|
message(STATUS "LIBS_FIND_DIRS: '${LIBS_FIND_DIRS}'")
|
||||||
|
message(STATUS "OUTPUT_DIR: '${OUTPUT_DIR}'")
|
||||||
|
message(STATUS "QT_VERSION_MAJOR: '${QT_VERSION_MAJOR}'")
|
||||||
|
message(STATUS "Find and copy dependencies. Please, wait...")
|
||||||
|
|
||||||
|
# functions --------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Копирование файла
|
||||||
|
|
||||||
|
function(safe_copy src dest)
|
||||||
|
|
||||||
|
# Пытаемся скопировать через execute_process (кросс-платформенно)
|
||||||
|
execute_process(
|
||||||
|
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${src}" "${dest}"
|
||||||
|
RESULT_VARIABLE copy_result
|
||||||
|
ERROR_VARIABLE copy_error
|
||||||
|
OUTPUT_QUIET # Подавляем stdout
|
||||||
|
)
|
||||||
|
|
||||||
|
if(NOT copy_result EQUAL 0)
|
||||||
|
message(WARNING "Не удалось скопировать ${src} -> ${dest}: ${copy_error}")
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# Отслеживание цепочки ссылок
|
||||||
|
|
||||||
|
function(get_symlink_chain dep symlink_chain)
|
||||||
|
unset(chain)
|
||||||
|
set(current_dep "${dep}")
|
||||||
|
|
||||||
|
# 1. Разрешаем основную цепочку симлинков (исходный файл → конечный файл)
|
||||||
|
while(IS_SYMLINK "${current_dep}")
|
||||||
|
execute_process(
|
||||||
|
COMMAND readlink "${current_dep}"
|
||||||
|
OUTPUT_VARIABLE link_target
|
||||||
|
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||||
|
)
|
||||||
|
list(INSERT chain 0 "${current_dep}") # Добавляем текущий симлинк в начало
|
||||||
|
get_filename_component(parent_dir "${current_dep}" DIRECTORY)
|
||||||
|
set(current_dep "${parent_dir}/${link_target}") # Переходим по ссылке
|
||||||
|
endwhile()
|
||||||
|
|
||||||
|
# 2. Добавляем конечный файл в начало цепочки
|
||||||
|
list(INSERT chain 0 "${current_dep}")
|
||||||
|
|
||||||
|
# 3. Теперь ищем ВСЕ симлинки в этой директории, которые ссылаются на конечный файл
|
||||||
|
if(EXISTS "${current_dep}")
|
||||||
|
get_filename_component(final_file "${current_dep}" REALPATH) # Абсолютный путь конечного файла
|
||||||
|
get_filename_component(parent_dir "${current_dep}" DIRECTORY) # Директория конечного файла
|
||||||
|
|
||||||
|
# Получаем список всех файлов в этой директории
|
||||||
|
file(GLOB all_files LIST_DIRECTORIES false "${parent_dir}/*")
|
||||||
|
foreach(file IN LISTS all_files)
|
||||||
|
# Если это симлинк, проверяем, ведёт ли он на конечный файл
|
||||||
|
if(IS_SYMLINK "${file}")
|
||||||
|
execute_process(
|
||||||
|
COMMAND readlink -f "${file}" # Абсолютный путь цели симлинка
|
||||||
|
OUTPUT_VARIABLE symlink_target
|
||||||
|
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||||
|
)
|
||||||
|
# Если цель симлинка совпадает с конечным файлом, добавляем в цепочку
|
||||||
|
if(symlink_target STREQUAL final_file AND NOT file IN_LIST chain)
|
||||||
|
list(APPEND chain "${file}")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(${symlink_chain} "${chain}" PARENT_SCOPE)
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
if (EXISTS "${TARGET_FILE}")
|
||||||
|
|
||||||
|
# Получаем runtime-зависимости
|
||||||
|
file(GET_RUNTIME_DEPENDENCIES
|
||||||
|
EXECUTABLES ${TARGET_FILE}
|
||||||
|
RESOLVED_DEPENDENCIES_VAR RESOLVED_DEPS
|
||||||
|
UNRESOLVED_DEPENDENCIES_VAR UNRESOLVED_DEPS
|
||||||
|
DIRECTORIES ${LIBS_FIND_DIRS}
|
||||||
|
)
|
||||||
|
|
||||||
|
set(USE_SQL OFF)
|
||||||
|
set(USE_PRINT OFF)
|
||||||
|
set(USE_NETWORK OFF)
|
||||||
|
set(USE_SERIALPORT OFF)
|
||||||
|
set(USE_MULTIMEDIA OFF)
|
||||||
|
|
||||||
|
message(STATUS "\nResolved dependencies copy:\n")
|
||||||
|
|
||||||
|
foreach(DEP ${RESOLVED_DEPS})
|
||||||
|
|
||||||
|
string(FIND "${DEP}" "${LIBS_FIND_DIRS}" POS)
|
||||||
|
|
||||||
|
if(POS EQUAL 0)
|
||||||
|
|
||||||
|
if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
|
||||||
|
|
||||||
|
message(STATUS "${DEP}")
|
||||||
|
file(COPY "${DEP}" DESTINATION "${OUTPUT_DIR}")
|
||||||
|
|
||||||
|
else ()
|
||||||
|
|
||||||
|
#message(STATUS "${DEP}")
|
||||||
|
#file(COPY "${DEP}" DESTINATION "${OUTPUT_DIR}/system_lib" FOLLOW_SYMLINK_CHAIN)
|
||||||
|
|
||||||
|
get_symlink_chain("${DEP}" dep_chain)
|
||||||
|
|
||||||
|
foreach(file IN LISTS dep_chain)
|
||||||
|
|
||||||
|
message(STATUS "${file}")
|
||||||
|
safe_copy("${file}" "${OUTPUT_DIR}")
|
||||||
|
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
endif()
|
||||||
|
|
||||||
|
endif()
|
||||||
|
|
||||||
|
string(FIND "${DEP}" "Qt${QT_VERSION_MAJOR}Sql" POS)
|
||||||
|
|
||||||
|
if(POS GREATER 0)
|
||||||
|
set(USE_SQL ON)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
string(FIND "${DEP}" "Qt${QT_VERSION_MAJOR}Print" POS)
|
||||||
|
|
||||||
|
if(POS GREATER 0)
|
||||||
|
set(USE_PRINT ON)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
string(FIND "${DEP}" "Qt${QT_VERSION_MAJOR}Network" POS)
|
||||||
|
|
||||||
|
if(POS GREATER 0)
|
||||||
|
set(USE_NETWORK ON)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
string(FIND "${DEP}" "Qt${QT_VERSION_MAJOR}Serial" POS)
|
||||||
|
|
||||||
|
if(POS GREATER 0)
|
||||||
|
set(USE_SERIALPORT ON)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
string(FIND "${DEP}" "Qt${QT_VERSION_MAJOR}Multimedia" POS)
|
||||||
|
|
||||||
|
if(POS GREATER 0)
|
||||||
|
set(USE_MULTIMEDIA ON)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
if (EXISTS "${LIBS_FIND_DIRS}/libQt${QT_VERSION_MAJOR}XcbQpa.so")
|
||||||
|
|
||||||
|
get_symlink_chain("${LIBS_FIND_DIRS}/libQt${QT_VERSION_MAJOR}XcbQpa.so" xcb_chain)
|
||||||
|
|
||||||
|
foreach(file IN LISTS xcb_chain)
|
||||||
|
|
||||||
|
message(STATUS "${file}")
|
||||||
|
safe_copy("${file}" "${OUTPUT_DIR}")
|
||||||
|
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
endif()
|
||||||
|
|
||||||
|
message(STATUS "\nResolved dependencies not copy:\n")
|
||||||
|
|
||||||
|
foreach(DEP ${RESOLVED_DEPS})
|
||||||
|
string(FIND "${DEP}" "${LIBS_FIND_DIRS}" POS)
|
||||||
|
if(NOT POS EQUAL 0)
|
||||||
|
message(STATUS "${DEP}")
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
message(STATUS "\nUnresolved dependencies:\n")
|
||||||
|
|
||||||
|
foreach(DEP ${UNRESOLVED_DEPS})
|
||||||
|
message(STATUS "${DEP}")
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
if (EXISTS "${QT_SHARE_DIR}/plugins/platforms")
|
||||||
|
file(COPY "${QT_SHARE_DIR}/plugins/platforms" DESTINATION "${OUTPUT_DIR}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (EXISTS "${QT_SHARE_DIR}/plugins/platformthemes")
|
||||||
|
file(COPY "${QT_SHARE_DIR}/plugins/platformthemes" DESTINATION "${OUTPUT_DIR}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (EXISTS "${QT_SHARE_DIR}/plugins/styles")
|
||||||
|
file(COPY "${QT_SHARE_DIR}/plugins/styles" DESTINATION "${OUTPUT_DIR}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (EXISTS "${QT_SHARE_DIR}/plugins/imageformats")
|
||||||
|
file(COPY "${QT_SHARE_DIR}/plugins/imageformats" DESTINATION "${OUTPUT_DIR}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (USE_SQL AND (EXISTS "${QT_SHARE_DIR}/plugins/sqldrivers"))
|
||||||
|
file(COPY "${QT_SHARE_DIR}/plugins/sqldrivers" DESTINATION "${OUTPUT_DIR}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (USE_PRINT AND (EXISTS "${QT_SHARE_DIR}/plugins/printsupport"))
|
||||||
|
file(COPY "${QT_SHARE_DIR}/plugins/printsupport" DESTINATION "${OUTPUT_DIR}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (USE_NETWORK AND (EXISTS "${QT_SHARE_DIR}/plugins/networkinformation"))
|
||||||
|
file(COPY "${QT_SHARE_DIR}/plugins/networkinformation" DESTINATION "${OUTPUT_DIR}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (USE_MULTIMEDIA AND (EXISTS "${QT_SHARE_DIR}/plugins/multimedia"))
|
||||||
|
file(COPY "${QT_SHARE_DIR}/plugins/multimedia" DESTINATION "${OUTPUT_DIR}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (EXISTS "${QT_SHARE_DIR}/translations")
|
||||||
|
|
||||||
|
file(MAKE_DIRECTORY "${OUTPUT_DIR}/translations")
|
||||||
|
|
||||||
|
if (EXISTS "${QT_SHARE_DIR}/translations/qtbase_ru.qm")
|
||||||
|
file(COPY "${QT_SHARE_DIR}/translations/qtbase_ru.qm" DESTINATION "${OUTPUT_DIR}/translations")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (EXISTS "${QT_SHARE_DIR}/translations/qtdeclarative_ru.qm")
|
||||||
|
file(COPY "${QT_SHARE_DIR}/translations/qtdeclarative_ru.qm" DESTINATION "${OUTPUT_DIR}/translations")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (USE_SERIALPORT AND (EXISTS "${QT_SHARE_DIR}/translations/qtserialport_ru.qm"))
|
||||||
|
file(COPY "${QT_SHARE_DIR}/translations/qtserialport_ru.qm" DESTINATION "${OUTPUT_DIR}/translations")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (USE_MULTIMEDIA AND (EXISTS "${QT_SHARE_DIR}/translations/qtmultimedia_ru.qm"))
|
||||||
|
file(COPY "${QT_SHARE_DIR}/translations/qtmultimedia_ru.qm" DESTINATION "${OUTPUT_DIR}/translations")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
endif()
|
||||||
|
|
||||||
|
else()
|
||||||
|
|
||||||
|
message(STATUS "'${TARGET_FILE}' not found. Exit.")
|
||||||
|
|
||||||
|
endif()
|
||||||
|
|
|
@ -0,0 +1,8 @@
|
||||||
|
|
||||||
|
if(NOT DEFINED SOFT_DEVELOPER OR "${SOFT_DEVELOPER}" STREQUAL "")
|
||||||
|
set(SOFT_DEVELOPER "Evgeny Teterin")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(NOT DEFINED DEVELOPER_DOMAIN OR "${DEVELOPER_DOMAIN}" STREQUAL "")
|
||||||
|
set(DEVELOPER_DOMAIN "poseon.ru")
|
||||||
|
endif()
|
|
@ -0,0 +1,29 @@
|
||||||
|
|
||||||
|
# Файл для подключения в основной проект через include
|
||||||
|
# Настройки для библиотек
|
||||||
|
|
||||||
|
include(${CMAKE_CURRENT_LIST_DIR}/common.cmake)
|
||||||
|
include(${CMAKE_CURRENT_LIST_DIR}/developer.cmake)
|
||||||
|
include(${CMAKE_CURRENT_LIST_DIR}/version.cmake)
|
||||||
|
|
||||||
|
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${DISTRIB_DIR})
|
||||||
|
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${DISTRIB_DIR})
|
||||||
|
|
||||||
|
if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
|
||||||
|
set(RUNTIME_OUTPUT_NAME lib${PROJECT_NAME}.dll)
|
||||||
|
configure_file(
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/versioninfo.rc.in
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/versioninfo.rc
|
||||||
|
@ONLY
|
||||||
|
)
|
||||||
|
else()
|
||||||
|
set(RUNTIME_OUTPUT_NAME lib${PROJECT_NAME}.so)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
configure_file(
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/config.h.in
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/config.h
|
||||||
|
@ONLY
|
||||||
|
)
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,40 @@
|
||||||
|
|
||||||
|
# Файл для подключения в основной проект через include
|
||||||
|
|
||||||
|
# Вспомогательные действия после сборки проекта
|
||||||
|
|
||||||
|
if(IS_DEBUG)
|
||||||
|
message(STATUS "Project '${PROJECT_NAME}' [post-build] DEBUG building: skip post-build actions")
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Включение/выключение поиска зависимостей:
|
||||||
|
set(COPY_DEPENDS ON)
|
||||||
|
|
||||||
|
get_target_property(TARGET_TYPE ${PROJECT_NAME} TYPE)
|
||||||
|
|
||||||
|
if(TARGET_TYPE STREQUAL "EXECUTABLE")
|
||||||
|
message(STATUS "${PROJECT_NAME} is an executable.")
|
||||||
|
elseif(TARGET_TYPE STREQUAL "STATIC_LIBRARY" OR TARGET_TYPE STREQUAL "SHARED_LIBRARY")
|
||||||
|
message(STATUS "${PROJECT_NAME} is a library.")
|
||||||
|
else()
|
||||||
|
message(STATUS "${PROJECT_NAME} is of another type: ${TARGET_TYPE}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (COPY_DEPENDS)
|
||||||
|
|
||||||
|
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
|
||||||
|
COMMAND ${CMAKE_COMMAND} -E echo "Copying runtime dependencies..."
|
||||||
|
COMMAND ${CMAKE_COMMAND}
|
||||||
|
-DTARGET_NAME="${RUNTIME_OUTPUT_NAME}"
|
||||||
|
-DTARGET_TYPE="${TARGET_TYPE}"
|
||||||
|
-DOUTPUT_DIR="${DISTRIB_DIR}"
|
||||||
|
-DPREFIX="${CMAKE_PREFIX_PATH}"
|
||||||
|
-DQT_VERSION_MAJOR=${QT_VERSION_MAJOR}
|
||||||
|
-DCMAKE_SYSTEM_NAME="${CMAKE_SYSTEM_NAME}"
|
||||||
|
-P "${CMAKE_INC_DIR}/copy_depends.cmake"
|
||||||
|
COMMENT "Copying runtime dependencies for ${PROJECT_NAME}"
|
||||||
|
)
|
||||||
|
|
||||||
|
endif()
|
||||||
|
|
|
@ -0,0 +1,25 @@
|
||||||
|
|
||||||
|
set(ROOT_PROJECT_DIR
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/..
|
||||||
|
)
|
||||||
|
|
||||||
|
cmake_path(NORMAL_PATH ROOT_PROJECT_DIR OUTPUT_VARIABLE ROOT_PROJECT_DIR)
|
||||||
|
|
||||||
|
set(CMAKE_INC_DIR
|
||||||
|
${ROOT_PROJECT_DIR}_cmake
|
||||||
|
)
|
||||||
|
|
||||||
|
set(RESOURCES_DIR
|
||||||
|
${ROOT_PROJECT_DIR}_resources
|
||||||
|
)
|
||||||
|
|
||||||
|
set(COMMON_SOURCES_DIR
|
||||||
|
${ROOT_PROJECT_DIR}_include
|
||||||
|
)
|
||||||
|
|
||||||
|
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
|
||||||
|
set(SYSTEM_INCLUDE_DIR "${CMAKE_PREFIX_PATH}/include")
|
||||||
|
else ()
|
||||||
|
set(SYSTEM_INCLUDE_DIR "/usr/include")
|
||||||
|
endif ()
|
||||||
|
|
|
@ -0,0 +1,55 @@
|
||||||
|
|
||||||
|
# Файл для подключения в основной проект через include
|
||||||
|
|
||||||
|
# Настройки компиляции для всего
|
||||||
|
|
||||||
|
if (DISABLE_HARD_WARNING_ERROR)
|
||||||
|
target_compile_options(${PROJECT_NAME} PRIVATE
|
||||||
|
-Wall
|
||||||
|
-Wextra
|
||||||
|
-Wpedantic
|
||||||
|
)
|
||||||
|
else()
|
||||||
|
target_compile_options(${PROJECT_NAME} PRIVATE
|
||||||
|
-Wall # Все стандартные предупреждения
|
||||||
|
-Wextra # Дополнительные предупреждения
|
||||||
|
-Wpedantic # Соответствие стандарту C++
|
||||||
|
-Werror # Превратить предупреждения в ошибки
|
||||||
|
-Wconversion # Предупреждения о неявных преобразованиях
|
||||||
|
-Wsign-conversion # Предупреждения о знаковых/беззнаковых преобразованиях
|
||||||
|
-Wshadow # Предупреждения о "тенях" переменных
|
||||||
|
-Wunused # Предупреждения о неиспользуемом коде
|
||||||
|
-Wold-style-cast # Запрет C-style кастов (только static_cast/dynamic_cast/...)
|
||||||
|
-Wnull-dereference # Предупреждения о возможных разыменованиях nullptr
|
||||||
|
-Wdouble-promotion # Предупреждения о неявном преобразовании float → double
|
||||||
|
-Wformat=2 # Строгая проверка printf/scanf
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
target_compile_definitions(${PROJECT_NAME} PRIVATE
|
||||||
|
QT_NO_FOREACH
|
||||||
|
QT_NO_URL_CAST_FROM_STRING
|
||||||
|
QT_NO_NARROWING_CONVERSIONS_IN_CONNECT
|
||||||
|
QT_STRICT_ITERATORS
|
||||||
|
)
|
||||||
|
|
||||||
|
find_program(CLANG_TIDY_EXE NAMES "clang-tidy")
|
||||||
|
|
||||||
|
if (CLANG_TIDY_EXE)
|
||||||
|
set(CMAKE_CXX_CLANG_TIDY "${CLANG_TIDY_EXE};-checks=*")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if (CMAKE_BUILD_TYPE STREQUAL "Debug" OR CMAKE_BUILD_TYPE STREQUAL "RelWithDebInfo")
|
||||||
|
target_compile_options(${PROJECT_NAME} PRIVATE
|
||||||
|
-fsanitize=address # AddressSanitizer (поиск утечек, выходов за границы)
|
||||||
|
-fsanitize=undefined # UndefinedBehaviorSanitizer (UB-проверки)
|
||||||
|
-fsanitize=leak # LeakSanitizer (поиск утечек памяти)
|
||||||
|
-fno-omit-frame-pointer # Для лучшего стека вызовов в санитайзерах
|
||||||
|
)
|
||||||
|
target_link_options(${PROJECT_NAME} PRIVATE
|
||||||
|
-fsanitize=address
|
||||||
|
-fsanitize=undefined
|
||||||
|
-fsanitize=leak
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
|
@ -0,0 +1,70 @@
|
||||||
|
|
||||||
|
# Файл для подключения в основной проект через include
|
||||||
|
|
||||||
|
# Обновление и генерация файлов переводов
|
||||||
|
# Языки переводов перечислить в переменной LNG
|
||||||
|
|
||||||
|
if(IS_DEBUG)
|
||||||
|
message(STATUS "Project '${PROJECT_NAME}' [translations] DEBUG building: skip .qm generation")
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Если список языков не задан в основном CMakeLists.txt — применяем по умолчанию
|
||||||
|
if(NOT DEFINED LNG)
|
||||||
|
set(LNG en ru)
|
||||||
|
message(STATUS "Project '${PROJECT_NAME}' [translations] LNG not set, use default: ${LNG}")
|
||||||
|
else()
|
||||||
|
message(STATUS "Project '${PROJECT_NAME}' [translations] Use LNG: ${LNG}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Подключить LinguistTools
|
||||||
|
find_package(Qt${QT_VERSION_MAJOR}LinguistTools REQUIRED)
|
||||||
|
|
||||||
|
# Полные пути утилит
|
||||||
|
get_target_property(LUPDATE_EXECUTABLE Qt${QT_VERSION_MAJOR}::lupdate IMPORTED_LOCATION)
|
||||||
|
get_target_property(LRELEASE_EXECUTABLE Qt${QT_VERSION_MAJOR}::lrelease IMPORTED_LOCATION)
|
||||||
|
|
||||||
|
# Каталог генерации файлов ts и qm файлов
|
||||||
|
set(TRANSLATIONS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/translations")
|
||||||
|
set(QM_OUTPUT_DIR "${DISTRIB_DIR}/translations")
|
||||||
|
file(MAKE_DIRECTORY "${TRANSLATIONS_DIR}")
|
||||||
|
file(MAKE_DIRECTORY "${QM_OUTPUT_DIR}")
|
||||||
|
|
||||||
|
# Список TS файлов в зависимости от списка языков
|
||||||
|
set(TS_FILES "")
|
||||||
|
|
||||||
|
# Обновление каждого файла с добавлением в список
|
||||||
|
foreach(LANG ${LNG})
|
||||||
|
|
||||||
|
set(TS_FILE "${TRANSLATIONS_DIR}/${PROJECT_NAME}_${LANG}.ts")
|
||||||
|
list(APPEND TS_FILES "${TS_FILE}")
|
||||||
|
message(STATUS "Project '${PROJECT_NAME}' Update translation file: ${TS_FILE}")
|
||||||
|
|
||||||
|
execute_process(COMMAND ${LUPDATE_EXECUTABLE}
|
||||||
|
${PROJECT_SOURCES}
|
||||||
|
-ts ${TS_FILE}
|
||||||
|
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||||
|
)
|
||||||
|
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
# Генерация файлов qm
|
||||||
|
set(QM_FILES "")
|
||||||
|
|
||||||
|
foreach(TS ${TS_FILES})
|
||||||
|
|
||||||
|
get_filename_component(TS_NAME_WE ${TS} NAME_WE)
|
||||||
|
set(QM ${QM_OUTPUT_DIR}/${TS_NAME_WE}.qm)
|
||||||
|
list(APPEND QM_FILES ${QM})
|
||||||
|
|
||||||
|
add_custom_command(
|
||||||
|
OUTPUT ${QM}
|
||||||
|
COMMAND ${LRELEASE_EXECUTABLE} ${TS} -qm ${QM}
|
||||||
|
DEPENDS ${TS}
|
||||||
|
COMMENT "Generating ${QM}"
|
||||||
|
)
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
add_custom_target(translations_qm ALL DEPENDS ${QM_FILES})
|
||||||
|
|
||||||
|
add_dependencies(translations_qm ${PROJECT_NAME})
|
|
@ -0,0 +1,52 @@
|
||||||
|
|
||||||
|
# Variables for generating the version.
|
||||||
|
# Used in the application (config.h file and versioninfo.rc)
|
||||||
|
#
|
||||||
|
|
||||||
|
# Получаем полный временной штамп в UTC (пример: "2025-04-16 12:33:58 UTC")
|
||||||
|
string(TIMESTAMP BUILD_DATE "%Y-%m-%d %H:%M:%S UTC" UTC)
|
||||||
|
string(TIMESTAMP VERSION_DOY "%j" UTC) # день в году (001..366)
|
||||||
|
|
||||||
|
# Извлекаем компоненты даты и времени
|
||||||
|
string(SUBSTRING "${BUILD_DATE}" 0 4 YEAR_STR)
|
||||||
|
string(SUBSTRING "${BUILD_DATE}" 2 2 VERSION_YY)
|
||||||
|
string(SUBSTRING "${BUILD_DATE}" 5 2 VERSION_MM)
|
||||||
|
string(SUBSTRING "${BUILD_DATE}" 8 2 VERSION_DD)
|
||||||
|
string(SUBSTRING "${BUILD_DATE}" 11 2 VERSION_HH)
|
||||||
|
string(SUBSTRING "${BUILD_DATE}" 14 2 VERSION_MIN)
|
||||||
|
string(SUBSTRING "${BUILD_DATE}" 17 2 VERSION_SS)
|
||||||
|
|
||||||
|
# Убираем ведущие нули путём преобразования в числа
|
||||||
|
math(EXPR VERSION_YY_NOZERO "${VERSION_YY}")
|
||||||
|
math(EXPR VERSION_MM_NOZERO "${VERSION_MM}")
|
||||||
|
math(EXPR VERSION_DD_NOZERO "${VERSION_DD}")
|
||||||
|
math(EXPR VERSION_HH_NOZERO "${VERSION_HH}")
|
||||||
|
math(EXPR VERSION_MIN_NOZERO "${VERSION_MIN}")
|
||||||
|
math(EXPR VERSION_SS_NOZERO "${VERSION_SS}")
|
||||||
|
math(EXPR VERSION_DOY_NOZERO "${VERSION_DOY}")
|
||||||
|
|
||||||
|
if (VERSION_FULLDATE)
|
||||||
|
# Полная дата: YY.MM.DD.NNN
|
||||||
|
|
||||||
|
# Считаем количество минут с начала суток
|
||||||
|
math(EXPR VERSION_NNN
|
||||||
|
"${VERSION_HH_NOZERO} * 60 + ${VERSION_MIN_NOZERO}"
|
||||||
|
)
|
||||||
|
|
||||||
|
set(PROJECT_VERSION_MAJOR ${VERSION_YY_NOZERO})
|
||||||
|
set(PROJECT_VERSION_MINOR ${VERSION_MM_NOZERO})
|
||||||
|
set(PROJECT_VERSION_PATCH ${VERSION_DD_NOZERO})
|
||||||
|
set(BUILD_NUM ${VERSION_NNN})
|
||||||
|
|
||||||
|
else()
|
||||||
|
# Версия от MAJOR, MINOR + YY + день года
|
||||||
|
# MAJOR и MINOR должны быть заданы ранее через `project(... VERSION ...)`
|
||||||
|
|
||||||
|
set(PROJECT_VERSION_PATCH ${VERSION_YY_NOZERO})
|
||||||
|
set(BUILD_NUM ${VERSION_DOY_NOZERO})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(ORIGINAL_FILE_NAME ${RUNTIME_OUTPUT_NAME})
|
||||||
|
|
||||||
|
message(STATUS "Project '${PROJECT_NAME}' version: ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}.${BUILD_NUM}")
|
||||||
|
|
|
@ -0,0 +1,35 @@
|
||||||
|
1 TYPELIB "versioninfo.rc"
|
||||||
|
|
||||||
|
1 VERSIONINFO
|
||||||
|
FILEVERSION @PROJECT_VERSION_MAJOR@, @PROJECT_VERSION_MINOR@, @PROJECT_VERSION_PATCH@, @BUILD_NUM@
|
||||||
|
PRODUCTVERSION @PROJECT_VERSION_MAJOR@, @PROJECT_VERSION_MINOR@, @PROJECT_VERSION_PATCH@, @BUILD_NUM@
|
||||||
|
FILEFLAGSMASK 0x3fL
|
||||||
|
#ifdef _DEBUG
|
||||||
|
FILEFLAGS 0x1L
|
||||||
|
#else
|
||||||
|
FILEFLAGS 0x0L
|
||||||
|
#endif
|
||||||
|
FILEOS 0x4L
|
||||||
|
FILETYPE 0x2L
|
||||||
|
FILESUBTYPE 0x0L
|
||||||
|
BEGIN
|
||||||
|
BLOCK "StringFileInfo"
|
||||||
|
BEGIN
|
||||||
|
BLOCK "040904e4"
|
||||||
|
BEGIN
|
||||||
|
VALUE "CompanyName", "@SOFT_DEVELOPER@"
|
||||||
|
VALUE "FileDescription", "@PROJECT_DESCRIPTION@"
|
||||||
|
VALUE "FileVersion","@PROJECT_VERSION_MAJOR@.@PROJECT_VERSION_MINOR@.@PROJECT_VERSION_PATCH@.@BUILD_NUM@"
|
||||||
|
VALUE "InternalName", "@PROJECT_NAME@"
|
||||||
|
VALUE "LegalCopyright", "Copyright (c) @YEAR_STR@ @SOFT_DEVELOPER@"
|
||||||
|
VALUE "OriginalFilename", "@ORIGINAL_FILE_NAME@"
|
||||||
|
VALUE "ProductName", "@PROJECT_NAME@"
|
||||||
|
VALUE "ProductVersion","@PROJECT_VERSION_MAJOR@.@PROJECT_VERSION_MINOR@.@PROJECT_VERSION_PATCH@.@BUILD_NUM@"
|
||||||
|
VALUE "BuildDate", "@BUILD_DATE@"
|
||||||
|
END
|
||||||
|
END
|
||||||
|
BLOCK "VarFileInfo"
|
||||||
|
BEGIN
|
||||||
|
VALUE "Translation", 0x409, 1252
|
||||||
|
END
|
||||||
|
END
|
|
@ -0,0 +1,225 @@
|
||||||
|
/****************************************************************************
|
||||||
|
** Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
|
||||||
|
** All right reserved.
|
||||||
|
**
|
||||||
|
** Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
** a copy of this software and associated documentation files (the
|
||||||
|
** "Software"), to deal in the Software without restriction, including
|
||||||
|
** without limitation the rights to use, copy, modify, merge, publish,
|
||||||
|
** distribute, sublicense, and/or sell copies of the Software, and to
|
||||||
|
** permit persons to whom the Software is furnished to do so, subject to
|
||||||
|
** the following conditions:
|
||||||
|
**
|
||||||
|
** The above copyright notice and this permission notice shall be
|
||||||
|
** included in all copies or substantial portions of the Software.
|
||||||
|
**
|
||||||
|
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||||
|
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||||
|
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||||
|
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||||
|
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
|
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
**
|
||||||
|
****************************************************************************/
|
||||||
|
#include "application_config.h"
|
||||||
|
#include "config.h"
|
||||||
|
#include <QtCore/QCoreApplication>
|
||||||
|
#include <QtCore/QTranslator>
|
||||||
|
#include <QtCore/QDebug>
|
||||||
|
#include <QtCore/QDir>
|
||||||
|
#include <QtCore/QStringList>
|
||||||
|
#include <QtCore/QStandardPaths>
|
||||||
|
|
||||||
|
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
|
||||||
|
# include <QtCore/QTextCodec>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
void Application::initialize()
|
||||||
|
{
|
||||||
|
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
|
||||||
|
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined (PROG_NAME)
|
||||||
|
QCoreApplication::setApplicationName( QString(PROG_NAME) );
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined (SOFT_DEVELOPER)
|
||||||
|
QCoreApplication::setOrganizationName( QString(SOFT_DEVELOPER) );
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined (DEVELOPER_DOMAIN)
|
||||||
|
QCoreApplication::setOrganizationDomain( QString(DEVELOPER_DOMAIN) );
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined (PROG_VERSION)
|
||||||
|
QCoreApplication::setApplicationVersion( QString(PROG_VERSION) );
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined (BUILD_DATE)
|
||||||
|
qApp->setProperty( "buildDate", QString(BUILD_DATE) );
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
QString Application::applicationRootPath()
|
||||||
|
{
|
||||||
|
QString path { QCoreApplication::applicationDirPath() };
|
||||||
|
|
||||||
|
if ( path.right(1) != "/" ) {
|
||||||
|
|
||||||
|
path += "/";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path.right(5) == "/bin/") {
|
||||||
|
|
||||||
|
path.remove( path.length() - 4, 4 );
|
||||||
|
}
|
||||||
|
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void Application::installTranslations(const QString &lng)
|
||||||
|
{
|
||||||
|
const QString dirName { applicationRootPath() + "translations/" };
|
||||||
|
QDir translationsDir { dirName };
|
||||||
|
|
||||||
|
QStringList filesList = translationsDir.entryList(
|
||||||
|
QStringList() << QString("*_%1.qm").arg(lng),
|
||||||
|
QDir::Files
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const QString &fileName: std::as_const(filesList)) {
|
||||||
|
|
||||||
|
QTranslator *translator = new QTranslator(QCoreApplication::instance());
|
||||||
|
|
||||||
|
if (translator->load( dirName + fileName )) {
|
||||||
|
|
||||||
|
QCoreApplication::instance()->installTranslator( translator );
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
|
||||||
|
delete translator;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
QString Application::applicationProfilePath()
|
||||||
|
{
|
||||||
|
QCoreApplication *application = QCoreApplication::instance();
|
||||||
|
if (!application) return QString();
|
||||||
|
|
||||||
|
if (!application->property("profilePath").isNull())
|
||||||
|
return application->property("profilePath").toString();
|
||||||
|
|
||||||
|
QString path = applicationRootPath();
|
||||||
|
QString profileDir;
|
||||||
|
QDir dir(path);
|
||||||
|
|
||||||
|
if (isPortable() && dir.mkpath(path + "profile")) {
|
||||||
|
|
||||||
|
profileDir = path + "profile/";
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
|
||||||
|
application->setProperty("isPortable", false);
|
||||||
|
|
||||||
|
profileDir = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/";
|
||||||
|
QString appDirectory = application->organizationName()
|
||||||
|
+ "/" + application->applicationName() + "/";
|
||||||
|
|
||||||
|
if (!profileDir.contains( appDirectory )) {
|
||||||
|
|
||||||
|
profileDir += appDirectory;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
application->setProperty("profilePath", profileDir);
|
||||||
|
return profileDir;
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
bool Application::isPortable()
|
||||||
|
{
|
||||||
|
QCoreApplication *application = QCoreApplication::instance();
|
||||||
|
if (!application) return false;
|
||||||
|
|
||||||
|
if (!application->property("isPortable").isNull())
|
||||||
|
return application->property("isPortable").toBool();
|
||||||
|
|
||||||
|
QFileInfo file(applicationRootPath() + "portable");
|
||||||
|
|
||||||
|
bool portable = (file.exists() && file.isFile()) || parameterExists("portable");
|
||||||
|
|
||||||
|
application->setProperty("isPortable", portable);
|
||||||
|
return portable;
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
bool Application::isDebug()
|
||||||
|
{
|
||||||
|
QCoreApplication *application = QCoreApplication::instance();
|
||||||
|
if (!application) return false;
|
||||||
|
|
||||||
|
if (!application->property("isDebug").isNull())
|
||||||
|
return application->property("isDebug").toBool();
|
||||||
|
|
||||||
|
QFileInfo file(applicationRootPath() + "debug");
|
||||||
|
|
||||||
|
bool debug = (file.exists() && file.isFile()) || parameterExists("debug");
|
||||||
|
|
||||||
|
application->setProperty("isDebug", debug);
|
||||||
|
return debug;
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
bool Application::parameterExists(const QString &name, const QString &shortName, QString *value)
|
||||||
|
{
|
||||||
|
QCoreApplication *application = QCoreApplication::instance();
|
||||||
|
if (!application) return false;
|
||||||
|
|
||||||
|
const QStringList params {application->arguments()};
|
||||||
|
int index {1};
|
||||||
|
|
||||||
|
while (index < params.size()) {
|
||||||
|
|
||||||
|
QString param = params.at(index);
|
||||||
|
++index;
|
||||||
|
|
||||||
|
while (!param.isEmpty() && ((param.at(0) == '/') || (param.at(0) == '-'))) {
|
||||||
|
|
||||||
|
param.remove(0, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (param.isEmpty()) continue;
|
||||||
|
|
||||||
|
if (!shortName.isEmpty() && (param == shortName)) {
|
||||||
|
|
||||||
|
if (value && (index < params.size())) *value = params.at(index);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
|
||||||
|
auto n = param.indexOf('=');
|
||||||
|
|
||||||
|
if (n > 0) {
|
||||||
|
|
||||||
|
QString val = param.mid(n + 1);
|
||||||
|
param = param.left(n);
|
||||||
|
|
||||||
|
if (param == name) {
|
||||||
|
|
||||||
|
if (value) *value = val;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (param == name) {
|
||||||
|
|
||||||
|
if (value && (index < params.size())) *value = params.at(index);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
//==============================================================================
|
|
@ -0,0 +1,51 @@
|
||||||
|
/****************************************************************************
|
||||||
|
** Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
|
||||||
|
** All right reserved.
|
||||||
|
**
|
||||||
|
** Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
** a copy of this software and associated documentation files (the
|
||||||
|
** "Software"), to deal in the Software without restriction, including
|
||||||
|
** without limitation the rights to use, copy, modify, merge, publish,
|
||||||
|
** distribute, sublicense, and/or sell copies of the Software, and to
|
||||||
|
** permit persons to whom the Software is furnished to do so, subject to
|
||||||
|
** the following conditions:
|
||||||
|
**
|
||||||
|
** The above copyright notice and this permission notice shall be
|
||||||
|
** included in all copies or substantial portions of the Software.
|
||||||
|
**
|
||||||
|
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||||
|
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||||
|
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||||
|
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||||
|
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
|
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
**
|
||||||
|
****************************************************************************/
|
||||||
|
#pragma once
|
||||||
|
#ifndef APP_CONFIG_H
|
||||||
|
#define APP_CONFIG_H
|
||||||
|
|
||||||
|
#include <QtCore/QString>
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
class Application
|
||||||
|
{
|
||||||
|
Q_DISABLE_COPY(Application)
|
||||||
|
|
||||||
|
public:
|
||||||
|
static void initialize();
|
||||||
|
static QString applicationRootPath();
|
||||||
|
static void installTranslations(const QString &lng = "ru");
|
||||||
|
static QString applicationProfilePath();
|
||||||
|
static bool isPortable();
|
||||||
|
static bool isDebug();
|
||||||
|
static bool parameterExists(const QString &name,
|
||||||
|
const QString &shortName = QString(),
|
||||||
|
QString *value = nullptr);
|
||||||
|
private:
|
||||||
|
Application() = delete;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif // APP_CONFIG_H
|
||||||
|
//==============================================================================
|
Binary file not shown.
After Width: | Height: | Size: 410 B |
Binary file not shown.
After Width: | Height: | Size: 5.3 KiB |
Binary file not shown.
After Width: | Height: | Size: 26 KiB |
Binary file not shown.
After Width: | Height: | Size: 51 KiB |
|
@ -0,0 +1,6 @@
|
||||||
|
<RCC>
|
||||||
|
<qresource prefix="/">
|
||||||
|
<file>images/main_icon.png</file>
|
||||||
|
<file>images/main_title.png</file>
|
||||||
|
</qresource>
|
||||||
|
</RCC>
|
|
@ -0,0 +1 @@
|
||||||
|
IDI_ICON1 ICON "main.ico"
|
|
@ -0,0 +1,81 @@
|
||||||
|
|
||||||
|
cmake_minimum_required(VERSION 4.0)
|
||||||
|
|
||||||
|
project(logger_example
|
||||||
|
VERSION 1.0
|
||||||
|
DESCRIPTION "Example use Logger lib"
|
||||||
|
LANGUAGES CXX
|
||||||
|
)
|
||||||
|
|
||||||
|
include(${CMAKE_CURRENT_SOURCE_DIR}/../_cmake/app_settings.cmake)
|
||||||
|
|
||||||
|
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS
|
||||||
|
Core Widgets
|
||||||
|
)
|
||||||
|
|
||||||
|
set(PROJECT_SOURCES
|
||||||
|
main.cpp
|
||||||
|
main_window.cpp
|
||||||
|
main_window.h
|
||||||
|
main_window.ui
|
||||||
|
${COMMON_SOURCES_DIR}/application_config.h
|
||||||
|
${COMMON_SOURCES_DIR}/application_config.cpp
|
||||||
|
)
|
||||||
|
|
||||||
|
set(PROJECT_RESOURCES
|
||||||
|
${RESOURCES_DIR}/main.qrc
|
||||||
|
)
|
||||||
|
|
||||||
|
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
|
||||||
|
set(PROJECT_RC_FILES
|
||||||
|
${RESOURCES_DIR}/main_icon.rc
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/versioninfo.rc
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
|
||||||
|
qt_add_executable(${PROJECT_NAME}
|
||||||
|
MANUAL_FINALIZATION
|
||||||
|
${PROJECT_SOURCES}
|
||||||
|
${PROJECT_RESOURCES}
|
||||||
|
${PROJECT_RC_FILES}
|
||||||
|
)
|
||||||
|
else()
|
||||||
|
add_executable(${PROJECT_NAME}
|
||||||
|
${PROJECT_SOURCES}
|
||||||
|
${PROJECT_RESOURCES}
|
||||||
|
${PROJECT_RC_FILES}
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
target_link_directories(${PROJECT_NAME} PRIVATE
|
||||||
|
${DISTRIB_DIR}
|
||||||
|
)
|
||||||
|
|
||||||
|
include(${CMAKE_INC_DIR}/target_options.cmake)
|
||||||
|
|
||||||
|
target_link_libraries(${PROJECT_NAME} PRIVATE
|
||||||
|
Qt${QT_VERSION_MAJOR}::Core
|
||||||
|
Qt${QT_VERSION_MAJOR}::Widgets
|
||||||
|
_logger
|
||||||
|
)
|
||||||
|
|
||||||
|
target_include_directories(${PROJECT_NAME} PRIVATE
|
||||||
|
${SYSTEM_INCLUDE_DIR}
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}
|
||||||
|
${COMMON_SOURCES_DIR}
|
||||||
|
${ROOT_PROJECT_DIR}lib_logger
|
||||||
|
)
|
||||||
|
|
||||||
|
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
|
||||||
|
set_target_properties(${PROJECT_NAME} PROPERTIES
|
||||||
|
WIN32_EXECUTABLE TRUE
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(QT_VERSION_MAJOR EQUAL 6)
|
||||||
|
qt_finalize_executable(${PROJECT_NAME})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
include(${CMAKE_INC_DIR}/post_build.cmake)
|
||||||
|
|
|
@ -0,0 +1,26 @@
|
||||||
|
#include "main_window.h"
|
||||||
|
#include <QtWidgets/QApplication>
|
||||||
|
#include "application_config.h"
|
||||||
|
#include "logger.h"
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
int main(int argc, char *argv[])
|
||||||
|
{
|
||||||
|
QApplication a(argc, argv);
|
||||||
|
|
||||||
|
Application::initialize();
|
||||||
|
Application::installTranslations();
|
||||||
|
|
||||||
|
// Создание главного окна:
|
||||||
|
MainWindow w;
|
||||||
|
|
||||||
|
// Запуск логгера:
|
||||||
|
Logger::instance().start();
|
||||||
|
|
||||||
|
w.show();
|
||||||
|
a.setQuitOnLastWindowClosed(true);
|
||||||
|
|
||||||
|
return a.exec();
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
|
|
@ -0,0 +1,163 @@
|
||||||
|
/****************************************************************************
|
||||||
|
** Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
|
||||||
|
** All right reserved.
|
||||||
|
**
|
||||||
|
** Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
** a copy of this software and associated documentation files (the
|
||||||
|
** "Software"), to deal in the Software without restriction, including
|
||||||
|
** without limitation the rights to use, copy, modify, merge, publish,
|
||||||
|
** distribute, sublicense, and/or sell copies of the Software, and to
|
||||||
|
** permit persons to whom the Software is furnished to do so, subject to
|
||||||
|
** the following conditions:
|
||||||
|
**
|
||||||
|
** The above copyright notice and this permission notice shall be
|
||||||
|
** included in all copies or substantial portions of the Software.
|
||||||
|
**
|
||||||
|
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||||
|
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||||
|
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||||
|
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||||
|
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
|
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
**
|
||||||
|
****************************************************************************/
|
||||||
|
#include "main_window.h"
|
||||||
|
#include "./ui_main_window.h"
|
||||||
|
#include <QtWidgets/QRadioButton>
|
||||||
|
#include <QtWidgets/QToolButton>
|
||||||
|
#include <QtWidgets/QLineEdit>
|
||||||
|
#include <QtWidgets/QPushButton>
|
||||||
|
#include <QtWidgets/QButtonGroup>
|
||||||
|
#include <QtCore/QDebug>
|
||||||
|
#include <QtCore/QLoggingCategory>
|
||||||
|
#include <QtGui/QDesktopServices>
|
||||||
|
#include <QtCore/QUrl>
|
||||||
|
#include <QtCore/QDir>
|
||||||
|
#include <QtWidgets/QMessageBox>
|
||||||
|
|
||||||
|
#include "logger.h"
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
Q_LOGGING_CATEGORY(mainWnd, "MainWindow")
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
MainWindow::MainWindow(QWidget *parent)
|
||||||
|
: QMainWindow(parent)
|
||||||
|
, ui(new Ui::MainWindow)
|
||||||
|
{
|
||||||
|
ui->setupUi(this);
|
||||||
|
initialize();
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
MainWindow::~MainWindow()
|
||||||
|
{
|
||||||
|
delete ui;
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void MainWindow::initialize()
|
||||||
|
{
|
||||||
|
setWindowTitle( QApplication::applicationName() );
|
||||||
|
|
||||||
|
connect(ui->radioButton1, &QRadioButton::toggled, this, &MainWindow::radioButtonToggled);
|
||||||
|
connect(ui->lineEdit1, &QLineEdit::editingFinished, this, &MainWindow::lineEditFinishEditing);
|
||||||
|
connect(ui->toolButton1, &QToolButton::clicked, this, &MainWindow::buttonClick);
|
||||||
|
connect(ui->pushButton1, &QPushButton::clicked, this, &MainWindow::buttonClick);
|
||||||
|
connect(ui->pushButton2, &QPushButton::clicked, this, &MainWindow::buttonClick);
|
||||||
|
connect(ui->pushButton2, &QPushButton::clicked, this, &MainWindow::buttonClick);
|
||||||
|
connect(ui->pushButtonOpen, &QPushButton::clicked, this, &MainWindow::buttonOpenClick);
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void MainWindow::radioButtonToggled(bool checked)
|
||||||
|
{
|
||||||
|
#ifndef QT_NO_DEBUG
|
||||||
|
LOG_FUNCTION();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
qCInfo(mainWnd) << "Переключение радиобаттона";
|
||||||
|
|
||||||
|
QAbstractButton *button = qobject_cast<QAbstractButton*>(sender());
|
||||||
|
|
||||||
|
if (button) {
|
||||||
|
|
||||||
|
qDebug() << "objectName:" << button->objectName()
|
||||||
|
<< "text: " << button->text()
|
||||||
|
<< "isChecked:" << checked;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
|
||||||
|
qCritical() << "Указатель не найден";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void MainWindow::lineEditFinishEditing()
|
||||||
|
{
|
||||||
|
#ifndef QT_NO_DEBUG
|
||||||
|
LOG_FUNCTION();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
qCInfo(mainWnd) << "Окончание редактирования текстового поля";
|
||||||
|
|
||||||
|
QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender());
|
||||||
|
|
||||||
|
if (lineEdit) {
|
||||||
|
|
||||||
|
qDebug() << "objectName:" << lineEdit->objectName()
|
||||||
|
<< "text: " << lineEdit->text();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
|
||||||
|
qCritical() << "Указатель не найден";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void MainWindow::buttonClick()
|
||||||
|
{
|
||||||
|
#ifndef QT_NO_DEBUG
|
||||||
|
LOG_FUNCTION();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
qCInfo(mainWnd) << "Нажатие кнопки";
|
||||||
|
|
||||||
|
QAbstractButton *button = qobject_cast<QAbstractButton*>(sender());
|
||||||
|
|
||||||
|
if (button) {
|
||||||
|
|
||||||
|
qDebug() << "objectName:" << button->objectName()
|
||||||
|
<< "text: " << button->text();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
|
||||||
|
qCritical() << "Указатель не найден";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void MainWindow::buttonOpenClick()
|
||||||
|
{
|
||||||
|
#ifndef QT_NO_DEBUG
|
||||||
|
LOG_FUNCTION();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
qCInfo(mainWnd) << "Нажатие кнопки открытия каталога логов";
|
||||||
|
|
||||||
|
QString path {Logger::logDirectory()};
|
||||||
|
QDir dir(path);
|
||||||
|
|
||||||
|
if (!dir.exists()) {
|
||||||
|
|
||||||
|
qWarning() << "Каталог не найден:" << path;
|
||||||
|
QMessageBox::critical(this, tr("Ошибка"), tr("Каталог не найден!"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool success = QDesktopServices::openUrl(QUrl::fromLocalFile(path));
|
||||||
|
|
||||||
|
if (!success) {
|
||||||
|
|
||||||
|
qWarning() << "Не удалось открыть каталог:" << path;
|
||||||
|
QMessageBox::critical(this, tr("Ошибка"), tr("Не удалось открыть каталог!"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//==============================================================================
|
|
@ -0,0 +1,63 @@
|
||||||
|
/****************************************************************************
|
||||||
|
** Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
|
||||||
|
** All right reserved.
|
||||||
|
**
|
||||||
|
** Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
** a copy of this software and associated documentation files (the
|
||||||
|
** "Software"), to deal in the Software without restriction, including
|
||||||
|
** without limitation the rights to use, copy, modify, merge, publish,
|
||||||
|
** distribute, sublicense, and/or sell copies of the Software, and to
|
||||||
|
** permit persons to whom the Software is furnished to do so, subject to
|
||||||
|
** the following conditions:
|
||||||
|
**
|
||||||
|
** The above copyright notice and this permission notice shall be
|
||||||
|
** included in all copies or substantial portions of the Software.
|
||||||
|
**
|
||||||
|
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||||
|
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||||
|
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||||
|
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||||
|
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
|
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
**
|
||||||
|
****************************************************************************/
|
||||||
|
#pragma once
|
||||||
|
#ifndef MAINWINDOW_H
|
||||||
|
#define MAINWINDOW_H
|
||||||
|
|
||||||
|
#include <QtWidgets/QMainWindow>
|
||||||
|
#include <QtWidgets/QAbstractButton>
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
QT_BEGIN_NAMESPACE
|
||||||
|
namespace Ui {
|
||||||
|
class MainWindow;
|
||||||
|
}
|
||||||
|
|
||||||
|
QT_END_NAMESPACE
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
// Главное окно
|
||||||
|
//==============================================================================
|
||||||
|
class MainWindow : public QMainWindow
|
||||||
|
{
|
||||||
|
Q_OBJECT
|
||||||
|
|
||||||
|
public:
|
||||||
|
MainWindow(QWidget *parent = nullptr);
|
||||||
|
~MainWindow();
|
||||||
|
|
||||||
|
private:
|
||||||
|
Ui::MainWindow *ui;
|
||||||
|
void initialize();
|
||||||
|
|
||||||
|
private slots:
|
||||||
|
void radioButtonToggled(bool checked);
|
||||||
|
void lineEditFinishEditing();
|
||||||
|
void buttonClick();
|
||||||
|
void buttonOpenClick();
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif // MAINWINDOW_H
|
||||||
|
//==============================================================================
|
|
@ -0,0 +1,197 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<ui version="4.0">
|
||||||
|
<class>MainWindow</class>
|
||||||
|
<widget class="QMainWindow" name="MainWindow">
|
||||||
|
<property name="geometry">
|
||||||
|
<rect>
|
||||||
|
<x>0</x>
|
||||||
|
<y>0</y>
|
||||||
|
<width>565</width>
|
||||||
|
<height>660</height>
|
||||||
|
</rect>
|
||||||
|
</property>
|
||||||
|
<property name="windowTitle">
|
||||||
|
<string>MainWindow</string>
|
||||||
|
</property>
|
||||||
|
<property name="windowIcon">
|
||||||
|
<iconset resource="../_resources/main.qrc">
|
||||||
|
<normaloff>:/images/main_icon.png</normaloff>:/images/main_icon.png</iconset>
|
||||||
|
</property>
|
||||||
|
<widget class="QWidget" name="centralwidget">
|
||||||
|
<layout class="QVBoxLayout" name="verticalLayout">
|
||||||
|
<property name="spacing">
|
||||||
|
<number>20</number>
|
||||||
|
</property>
|
||||||
|
<item>
|
||||||
|
<widget class="QLabel" name="label_2">
|
||||||
|
<property name="text">
|
||||||
|
<string><html><head/><body><p align="justify">Приложение использует библиотеку <span style=" font-weight:700;">lib_logger</span> для сохранения лога в файл. Логирование событий осуществляется через стандартный механизм Qt:</p><p>qInfo() &lt;&lt; &quot;Строка информации&quot;;</p><p>qDebug() &lt;&lt; &quot;Строка отладки&quot;;</p><p>qWarning() &lt;&lt; &quot;Строка предупреждения&quot;;</p><p>qCritical() &lt;&lt; &quot;Строка ошибки&quot;;</p><p align="justify">Строки отладки (qDebug, qCDebug) сохраняются только если приложение запущено с параметром /debug или в каталоге ПО находится файл <span style=" font-weight:700;">debug</span> (без расширения с любым содержанием).</p><p align="justify">Логи сохраняются в каталоге профиля приложения. Если в каталоге ПО находится файл <span style=" font-weight:700;">portable</span> (без расширения с любым содержанием), то каталог логов будет создан в подкаталоге <span style=" font-weight:700;">profile</span> каталога ПО.</p></body></html></string>
|
||||||
|
</property>
|
||||||
|
<property name="wordWrap">
|
||||||
|
<bool>true</bool>
|
||||||
|
</property>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
<item>
|
||||||
|
<widget class="QGroupBox" name="groupBox1">
|
||||||
|
<property name="title">
|
||||||
|
<string>Пример логирования событий</string>
|
||||||
|
</property>
|
||||||
|
<layout class="QVBoxLayout" name="verticalLayout_2">
|
||||||
|
<property name="spacing">
|
||||||
|
<number>40</number>
|
||||||
|
</property>
|
||||||
|
<property name="leftMargin">
|
||||||
|
<number>20</number>
|
||||||
|
</property>
|
||||||
|
<property name="topMargin">
|
||||||
|
<number>20</number>
|
||||||
|
</property>
|
||||||
|
<property name="rightMargin">
|
||||||
|
<number>20</number>
|
||||||
|
</property>
|
||||||
|
<property name="bottomMargin">
|
||||||
|
<number>20</number>
|
||||||
|
</property>
|
||||||
|
<item>
|
||||||
|
<layout class="QGridLayout" name="gridLayout">
|
||||||
|
<property name="spacing">
|
||||||
|
<number>10</number>
|
||||||
|
</property>
|
||||||
|
<item row="0" column="0">
|
||||||
|
<widget class="QRadioButton" name="radioButton1">
|
||||||
|
<property name="text">
|
||||||
|
<string>Вариант 1</string>
|
||||||
|
</property>
|
||||||
|
<property name="checked">
|
||||||
|
<bool>true</bool>
|
||||||
|
</property>
|
||||||
|
<attribute name="buttonGroup">
|
||||||
|
<string notr="true">buttonGroup</string>
|
||||||
|
</attribute>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
<item row="0" column="1">
|
||||||
|
<widget class="QLabel" name="label">
|
||||||
|
<property name="text">
|
||||||
|
<string>Ввод текста:</string>
|
||||||
|
</property>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
<item row="1" column="0">
|
||||||
|
<widget class="QRadioButton" name="radioButton2">
|
||||||
|
<property name="text">
|
||||||
|
<string>Вариант 2</string>
|
||||||
|
</property>
|
||||||
|
<attribute name="buttonGroup">
|
||||||
|
<string notr="true">buttonGroup</string>
|
||||||
|
</attribute>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
<item row="1" column="1">
|
||||||
|
<widget class="QLineEdit" name="lineEdit1"/>
|
||||||
|
</item>
|
||||||
|
<item row="1" column="2">
|
||||||
|
<widget class="QToolButton" name="toolButton1">
|
||||||
|
<property name="minimumSize">
|
||||||
|
<size>
|
||||||
|
<width>30</width>
|
||||||
|
<height>24</height>
|
||||||
|
</size>
|
||||||
|
</property>
|
||||||
|
<property name="text">
|
||||||
|
<string>...</string>
|
||||||
|
</property>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
</layout>
|
||||||
|
</item>
|
||||||
|
<item>
|
||||||
|
<layout class="QGridLayout" name="gridLayout_2" columnstretch="1,2,1">
|
||||||
|
<property name="verticalSpacing">
|
||||||
|
<number>20</number>
|
||||||
|
</property>
|
||||||
|
<item row="0" column="0">
|
||||||
|
<spacer name="horizontalSpacer">
|
||||||
|
<property name="orientation">
|
||||||
|
<enum>Qt::Orientation::Horizontal</enum>
|
||||||
|
</property>
|
||||||
|
<property name="sizeHint" stdset="0">
|
||||||
|
<size>
|
||||||
|
<width>40</width>
|
||||||
|
<height>20</height>
|
||||||
|
</size>
|
||||||
|
</property>
|
||||||
|
</spacer>
|
||||||
|
</item>
|
||||||
|
<item row="0" column="1">
|
||||||
|
<widget class="QPushButton" name="pushButton1">
|
||||||
|
<property name="text">
|
||||||
|
<string>Кнопка 1</string>
|
||||||
|
</property>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
<item row="0" column="2">
|
||||||
|
<spacer name="horizontalSpacer_2">
|
||||||
|
<property name="orientation">
|
||||||
|
<enum>Qt::Orientation::Horizontal</enum>
|
||||||
|
</property>
|
||||||
|
<property name="sizeHint" stdset="0">
|
||||||
|
<size>
|
||||||
|
<width>40</width>
|
||||||
|
<height>20</height>
|
||||||
|
</size>
|
||||||
|
</property>
|
||||||
|
</spacer>
|
||||||
|
</item>
|
||||||
|
<item row="1" column="1">
|
||||||
|
<widget class="QPushButton" name="pushButton2">
|
||||||
|
<property name="text">
|
||||||
|
<string>Кнопка 2</string>
|
||||||
|
</property>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
<item row="2" column="1">
|
||||||
|
<widget class="QPushButton" name="pushButton3">
|
||||||
|
<property name="text">
|
||||||
|
<string>Кнопка 3</string>
|
||||||
|
</property>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
<item row="3" column="1">
|
||||||
|
<spacer name="verticalSpacer">
|
||||||
|
<property name="orientation">
|
||||||
|
<enum>Qt::Orientation::Vertical</enum>
|
||||||
|
</property>
|
||||||
|
<property name="sizeHint" stdset="0">
|
||||||
|
<size>
|
||||||
|
<width>20</width>
|
||||||
|
<height>28</height>
|
||||||
|
</size>
|
||||||
|
</property>
|
||||||
|
</spacer>
|
||||||
|
</item>
|
||||||
|
<item row="4" column="1">
|
||||||
|
<widget class="QPushButton" name="pushButtonOpen">
|
||||||
|
<property name="text">
|
||||||
|
<string>Открыть каталог с логами</string>
|
||||||
|
</property>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
</layout>
|
||||||
|
</item>
|
||||||
|
</layout>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
</layout>
|
||||||
|
</widget>
|
||||||
|
<widget class="QStatusBar" name="statusbar"/>
|
||||||
|
</widget>
|
||||||
|
<resources>
|
||||||
|
<include location="../_resources/main.qrc"/>
|
||||||
|
</resources>
|
||||||
|
<connections/>
|
||||||
|
<buttongroups>
|
||||||
|
<buttongroup name="buttonGroup"/>
|
||||||
|
</buttongroups>
|
||||||
|
</ui>
|
|
@ -0,0 +1,57 @@
|
||||||
|
cmake_minimum_required(VERSION 4.0)
|
||||||
|
|
||||||
|
project(_logger
|
||||||
|
VERSION 1.0
|
||||||
|
DESCRIPTION "Logger library for Qt projects"
|
||||||
|
LANGUAGES CXX)
|
||||||
|
|
||||||
|
include(${CMAKE_CURRENT_SOURCE_DIR}/../_cmake/lib_settings.cmake)
|
||||||
|
|
||||||
|
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS
|
||||||
|
Core
|
||||||
|
)
|
||||||
|
|
||||||
|
set(PUBLIC_LIBRARY_HEADERS
|
||||||
|
logger.h
|
||||||
|
)
|
||||||
|
|
||||||
|
set(PROJECT_SOURCES
|
||||||
|
private/logger.cpp
|
||||||
|
private/log_worker.h
|
||||||
|
${COMMON_SOURCES_DIR}/application_config.h
|
||||||
|
${COMMON_SOURCES_DIR}/application_config.cpp
|
||||||
|
)
|
||||||
|
|
||||||
|
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
|
||||||
|
set(PROJECT_RC_FILES
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/versioninfo.rc
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
add_library(${PROJECT_NAME} SHARED
|
||||||
|
${PUBLIC_LIBRARY_HEADERS}
|
||||||
|
${PROJECT_SOURCES}
|
||||||
|
${PROJECT_RC_FILES}
|
||||||
|
)
|
||||||
|
|
||||||
|
include(${CMAKE_INC_DIR}/target_options.cmake)
|
||||||
|
|
||||||
|
target_include_directories(${PROJECT_NAME} PRIVATE
|
||||||
|
${SYSTEM_INCLUDE_DIR}
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}
|
||||||
|
${COMMON_SOURCES_DIR}
|
||||||
|
${CMAKE_CURRENT_SOURCE_DIR}/private
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_directories(${PROJECT_NAME} PRIVATE
|
||||||
|
${CMAKE_LIBRARY_OUTPUT_DIRECTORY}
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_libraries(${PROJECT_NAME} PRIVATE
|
||||||
|
Qt${QT_VERSION_MAJOR}::Core
|
||||||
|
)
|
||||||
|
|
||||||
|
target_compile_definitions(${PROJECT_NAME} PRIVATE
|
||||||
|
LIB_LOGGER
|
||||||
|
)
|
||||||
|
|
|
@ -0,0 +1,107 @@
|
||||||
|
/****************************************************************************
|
||||||
|
** Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
|
||||||
|
** All right reserved.
|
||||||
|
**
|
||||||
|
** Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
** a copy of this software and associated documentation files (the
|
||||||
|
** "Software"), to deal in the Software without restriction, including
|
||||||
|
** without limitation the rights to use, copy, modify, merge, publish,
|
||||||
|
** distribute, sublicense, and/or sell copies of the Software, and to
|
||||||
|
** permit persons to whom the Software is furnished to do so, subject to
|
||||||
|
** the following conditions:
|
||||||
|
**
|
||||||
|
** The above copyright notice and this permission notice shall be
|
||||||
|
** included in all copies or substantial portions of the Software.
|
||||||
|
**
|
||||||
|
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||||
|
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||||
|
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||||
|
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||||
|
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
|
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
**
|
||||||
|
****************************************************************************/
|
||||||
|
#pragma once
|
||||||
|
#ifndef LOGGER_H
|
||||||
|
#define LOGGER_H
|
||||||
|
|
||||||
|
#if defined (LIB_LOGGER)
|
||||||
|
# define LOGGER_EXPORT Q_DECL_EXPORT
|
||||||
|
#else
|
||||||
|
# define LOGGER_EXPORT Q_DECL_IMPORT
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include <QtCore/QObject>
|
||||||
|
#include <QtCore/QString>
|
||||||
|
#include <QtCore/QLoggingCategory>
|
||||||
|
#include <QtCore/QThread>
|
||||||
|
#include <atomic>
|
||||||
|
|
||||||
|
class LogWorker;
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
class LOGGER_EXPORT Logger : public QObject
|
||||||
|
{
|
||||||
|
Q_OBJECT
|
||||||
|
Q_DISABLE_COPY(Logger)
|
||||||
|
|
||||||
|
public:
|
||||||
|
enum class LogType: quint8 {
|
||||||
|
LogInfo = 0, // Информация
|
||||||
|
LogWarning = 1, // Предупреждение
|
||||||
|
LogError = 2, // Ошибка
|
||||||
|
LogInput = 3, // Входящие данные
|
||||||
|
LogOutput = 4, // Исходящие данные
|
||||||
|
LogDebug = 5 // Отладочная информация
|
||||||
|
};
|
||||||
|
Q_ENUM(LogType)
|
||||||
|
|
||||||
|
static bool isRunning();
|
||||||
|
static Logger& instance();
|
||||||
|
static QString logTypeToString(LogType logType);
|
||||||
|
static QString logTypeToString(quint8 logType);
|
||||||
|
static LogType stringToLogType(const QString &stringType);
|
||||||
|
static LogType qtMsgToLogType(QtMsgType type);
|
||||||
|
static const QLoggingCategory &inputData();
|
||||||
|
static const QLoggingCategory &outputData();
|
||||||
|
static QString logDirectory();
|
||||||
|
|
||||||
|
public slots:
|
||||||
|
void start();
|
||||||
|
void stop();
|
||||||
|
void writeLogQtType(QtMsgType type, const QMessageLogContext &context, const QString &msg);
|
||||||
|
void writeLog(const QString &msg, LogType type = LogType::LogInfo, const QString &objectName = QString());
|
||||||
|
|
||||||
|
private:
|
||||||
|
const int maximumLogCount {100};
|
||||||
|
|
||||||
|
LogWorker *logWorker {nullptr};
|
||||||
|
QThread *workThread {nullptr};
|
||||||
|
explicit Logger(QObject *parent = nullptr);
|
||||||
|
virtual ~Logger();
|
||||||
|
};
|
||||||
|
//==============================================================================
|
||||||
|
class LOGGER_EXPORT FunctionLogger
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
explicit FunctionLogger(const char *file,
|
||||||
|
int line,
|
||||||
|
const char *name,
|
||||||
|
const QLoggingCategory &category = QLoggingCategory("Function"));
|
||||||
|
~FunctionLogger();
|
||||||
|
private:
|
||||||
|
static std::atomic<size_t> counter;
|
||||||
|
size_t id;
|
||||||
|
QString functionName;
|
||||||
|
QString logCategory;
|
||||||
|
};
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
#define LOG_FUNCTION(...) FunctionLogger funcLogger(__FILE__, __LINE__, __PRETTY_FUNCTION__ __VA_OPT__(, __VA_ARGS__))
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
|
||||||
|
Q_DECLARE_METATYPE(Logger::LogType)
|
||||||
|
|
||||||
|
#endif // LOGGER_H
|
|
@ -0,0 +1,85 @@
|
||||||
|
/****************************************************************************
|
||||||
|
** Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
|
||||||
|
** All right reserved.
|
||||||
|
**
|
||||||
|
** Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
** a copy of this software and associated documentation files (the
|
||||||
|
** "Software"), to deal in the Software without restriction, including
|
||||||
|
** without limitation the rights to use, copy, modify, merge, publish,
|
||||||
|
** distribute, sublicense, and/or sell copies of the Software, and to
|
||||||
|
** permit persons to whom the Software is furnished to do so, subject to
|
||||||
|
** the following conditions:
|
||||||
|
**
|
||||||
|
** The above copyright notice and this permission notice shall be
|
||||||
|
** included in all copies or substantial portions of the Software.
|
||||||
|
**
|
||||||
|
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||||
|
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||||
|
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||||
|
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||||
|
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
|
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
**
|
||||||
|
****************************************************************************/
|
||||||
|
#pragma once
|
||||||
|
#ifndef LOG_WORKER_H
|
||||||
|
#define LOG_WORKER_H
|
||||||
|
|
||||||
|
#include <QtCore/QObject>
|
||||||
|
#include <QtCore/QString>
|
||||||
|
#include <QtCore/QMutex>
|
||||||
|
#include <QtCore/QFile>
|
||||||
|
#include <QtCore/QDateTime>
|
||||||
|
#include <QtCore/QQueue>
|
||||||
|
#include <QtCore/QTimer>
|
||||||
|
#include <atomic>
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
class LogWorker : public QObject
|
||||||
|
{
|
||||||
|
Q_OBJECT
|
||||||
|
public:
|
||||||
|
explicit LogWorker(const QString &logFilePath, QObject *parent = nullptr);
|
||||||
|
virtual ~LogWorker();
|
||||||
|
|
||||||
|
signals:
|
||||||
|
void started();
|
||||||
|
void stopped();
|
||||||
|
|
||||||
|
public slots:
|
||||||
|
Q_INVOKABLE void start();
|
||||||
|
Q_INVOKABLE void stop();
|
||||||
|
Q_INVOKABLE void writeLog(const QString &msg,
|
||||||
|
int type = 0,
|
||||||
|
const QString &objectName = QString());
|
||||||
|
private slots:
|
||||||
|
void checkQueue();
|
||||||
|
|
||||||
|
private:
|
||||||
|
const int queueIntervalMs {5000};
|
||||||
|
struct LogRecord {
|
||||||
|
int type {0};
|
||||||
|
QString msg;
|
||||||
|
QString objectName;
|
||||||
|
QDateTime dateTime;
|
||||||
|
};
|
||||||
|
std::atomic<bool> running {false};
|
||||||
|
qint64 linesCounter {0};
|
||||||
|
qint64 linesPosition {0};
|
||||||
|
QFile file;
|
||||||
|
QMutex mutex;
|
||||||
|
QDateTime startTime;
|
||||||
|
QQueue<LogRecord> queue;
|
||||||
|
QTimer *timer {nullptr};
|
||||||
|
//
|
||||||
|
void writeFirstLines();
|
||||||
|
void writeLastLines();
|
||||||
|
void writeLine(const QString &msg, int type = 0,
|
||||||
|
const QString &objectName = QString(),
|
||||||
|
const QDateTime &dateTime = QDateTime::currentDateTime());
|
||||||
|
void writeAllFromQueue();
|
||||||
|
};
|
||||||
|
//==============================================================================
|
||||||
|
|
||||||
|
#endif // LOG_WORKER_H
|
|
@ -0,0 +1,605 @@
|
||||||
|
/****************************************************************************
|
||||||
|
** Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
|
||||||
|
** All right reserved.
|
||||||
|
**
|
||||||
|
** Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
** a copy of this software and associated documentation files (the
|
||||||
|
** "Software"), to deal in the Software without restriction, including
|
||||||
|
** without limitation the rights to use, copy, modify, merge, publish,
|
||||||
|
** distribute, sublicense, and/or sell copies of the Software, and to
|
||||||
|
** permit persons to whom the Software is furnished to do so, subject to
|
||||||
|
** the following conditions:
|
||||||
|
**
|
||||||
|
** The above copyright notice and this permission notice shall be
|
||||||
|
** included in all copies or substantial portions of the Software.
|
||||||
|
**
|
||||||
|
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||||
|
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||||
|
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||||
|
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||||
|
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
|
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
**
|
||||||
|
****************************************************************************/
|
||||||
|
#include "logger.h"
|
||||||
|
|
||||||
|
#include <QtCore/QMetaType>
|
||||||
|
#include <QtCore/QMetaObject>
|
||||||
|
#include <QtCore/QCoreApplication>
|
||||||
|
#include <QtCore/QDir>
|
||||||
|
#include <QtCore/QDebug>
|
||||||
|
#include <QtCore/QDateTime>
|
||||||
|
#include <QtCore/QMutexLocker>
|
||||||
|
#include <QtCore/QMetaEnum>
|
||||||
|
#include <QtCore/QTextStream>
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
|
#include "log_worker.h"
|
||||||
|
#include "application_config.h"
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
std::atomic<size_t> FunctionLogger::counter {0};
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
void qtLogMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
|
||||||
|
{
|
||||||
|
if ((type == QtWarningMsg) || (type == QtCriticalMsg) || (type == QtFatalMsg)) {
|
||||||
|
|
||||||
|
std::cerr << msg.toLocal8Bit().constData() << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger::instance().writeLogQtType(type, context, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
//
|
||||||
|
// Logger - general class
|
||||||
|
//
|
||||||
|
//==============================================================================
|
||||||
|
bool Logger::isRunning()
|
||||||
|
{
|
||||||
|
QCoreApplication *application = QCoreApplication::instance();
|
||||||
|
|
||||||
|
return application
|
||||||
|
&& !application->property("loggerRun").isNull()
|
||||||
|
&& application->property("loggerRun").toBool();
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
Logger &Logger::instance()
|
||||||
|
{
|
||||||
|
static Logger loggerInstance;
|
||||||
|
return loggerInstance;
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
QString Logger::logTypeToString(LogType logType)
|
||||||
|
{
|
||||||
|
switch (logType) {
|
||||||
|
case LogType::LogInfo:
|
||||||
|
return "[inf]";
|
||||||
|
case LogType::LogWarning:
|
||||||
|
return "[wrn]";
|
||||||
|
case LogType::LogError:
|
||||||
|
return "[err]";
|
||||||
|
case LogType::LogInput:
|
||||||
|
return "[<<<]";
|
||||||
|
case LogType::LogOutput:
|
||||||
|
return "[>>>]";
|
||||||
|
case LogType::LogDebug:
|
||||||
|
return "[dbg]";
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return "[inf]";
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
QString Logger::logTypeToString(quint8 logType)
|
||||||
|
{
|
||||||
|
QMetaEnum metaEnum = QMetaEnum::fromType<Logger::LogType>();
|
||||||
|
const char* name = metaEnum.valueToKey(logType);
|
||||||
|
|
||||||
|
if (!name) {
|
||||||
|
|
||||||
|
return "[inf]";
|
||||||
|
}
|
||||||
|
|
||||||
|
return logTypeToString( static_cast<LogType>(logType) );
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
Logger::LogType Logger::qtMsgToLogType(QtMsgType type)
|
||||||
|
{
|
||||||
|
switch (type) {
|
||||||
|
case QtDebugMsg:
|
||||||
|
return Logger::LogType::LogDebug;
|
||||||
|
case QtInfoMsg:
|
||||||
|
return Logger::LogType::LogInfo;
|
||||||
|
case QtWarningMsg:
|
||||||
|
return Logger::LogType::LogWarning;
|
||||||
|
case QtCriticalMsg:
|
||||||
|
return Logger::LogType::LogError;
|
||||||
|
case QtFatalMsg:
|
||||||
|
return Logger::LogType::LogError;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Logger::LogType::LogInfo;
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
const QLoggingCategory &Logger::inputData()
|
||||||
|
{
|
||||||
|
static const QLoggingCategory category("input");
|
||||||
|
return category;
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
const QLoggingCategory &Logger::outputData()
|
||||||
|
{
|
||||||
|
static const QLoggingCategory category("output");
|
||||||
|
return category;
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
QString Logger::logDirectory()
|
||||||
|
{
|
||||||
|
return Application::applicationProfilePath() + "log/";
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void Logger::start()
|
||||||
|
{
|
||||||
|
if (logWorker || workThread) return;
|
||||||
|
|
||||||
|
QString logDir { logDirectory() };
|
||||||
|
QDir logPath {logDir};
|
||||||
|
|
||||||
|
if (!logPath.mkpath(logDir)) {
|
||||||
|
|
||||||
|
qCritical() << "Error make path: " << logDir;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
QDateTime startDateTime {QDateTime::currentDateTime()};
|
||||||
|
|
||||||
|
QString logFileName {startDateTime.toString("yyMMdd_HHmmss_zzz") + ".log"};
|
||||||
|
|
||||||
|
logWorker = new LogWorker(logDir + logFileName, nullptr);
|
||||||
|
workThread = new QThread(this);
|
||||||
|
logWorker->moveToThread(workThread);
|
||||||
|
|
||||||
|
connect(workThread, &QThread::started, logWorker, &LogWorker::start, Qt::QueuedConnection);
|
||||||
|
connect(logWorker, &LogWorker::stopped, workThread, &QThread::quit);
|
||||||
|
|
||||||
|
workThread->start();
|
||||||
|
|
||||||
|
qInstallMessageHandler( qtLogMessageOutput );
|
||||||
|
|
||||||
|
writeLog(tr("Удаление старых лог файлов из '%1', "
|
||||||
|
"количество сохраняемых лог файлов: %2")
|
||||||
|
.arg(logDir).arg(maximumLogCount));
|
||||||
|
QDir dir(logDir);
|
||||||
|
QStringList list = dir.entryList(QStringList() << "*.log",
|
||||||
|
QDir::Files | QDir::Writable,
|
||||||
|
QDir::Name);
|
||||||
|
writeLog(tr("Найдено лог файлов: %1").arg(list.size()), LogType::LogDebug);
|
||||||
|
|
||||||
|
while (list.size() > maximumLogCount) {
|
||||||
|
|
||||||
|
QString fileName = list.takeFirst();
|
||||||
|
|
||||||
|
if (QFile::remove(logDir + fileName)) {
|
||||||
|
|
||||||
|
writeLog(tr("Удаление файла '%1'").arg(fileName), LogType::LogDebug);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
|
||||||
|
writeLog(tr("Ошибка при удалении файла '%1'").arg(fileName), LogType::LogError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void Logger::stop()
|
||||||
|
{
|
||||||
|
if (!logWorker && !workThread) return;
|
||||||
|
|
||||||
|
qInstallMessageHandler(0);
|
||||||
|
|
||||||
|
if (logWorker) {
|
||||||
|
|
||||||
|
QMetaObject::invokeMethod(
|
||||||
|
logWorker,
|
||||||
|
&LogWorker::stop,
|
||||||
|
Qt::QueuedConnection
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (workThread && workThread->isRunning()) {
|
||||||
|
|
||||||
|
if (!workThread->wait(1500)) {
|
||||||
|
|
||||||
|
workThread->quit();
|
||||||
|
|
||||||
|
if (!workThread->wait(1500)) {
|
||||||
|
|
||||||
|
workThread->terminate();
|
||||||
|
workThread->wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (workThread) delete workThread;
|
||||||
|
if (logWorker) delete logWorker;
|
||||||
|
|
||||||
|
workThread = nullptr;
|
||||||
|
logWorker = nullptr;
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void Logger::writeLogQtType(QtMsgType type, const QMessageLogContext &context, const QString &msg)
|
||||||
|
{
|
||||||
|
if (!logWorker) return;
|
||||||
|
|
||||||
|
QString category(context.category);
|
||||||
|
LogType logType {LogType::LogInfo};
|
||||||
|
QString objectName;
|
||||||
|
|
||||||
|
if (category.indexOf("input") == 0) {
|
||||||
|
|
||||||
|
logType = LogType::LogInput;
|
||||||
|
|
||||||
|
if (category.length() > 5) objectName = category.mid(5);
|
||||||
|
}
|
||||||
|
else if (category.indexOf("output") == 0) {
|
||||||
|
|
||||||
|
logType = LogType::LogOutput;
|
||||||
|
|
||||||
|
if (category.length() > 6) objectName = category.mid(6);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
|
||||||
|
logType = qtMsgToLogType(type);
|
||||||
|
|
||||||
|
if (!category.isEmpty() && (category != "default")) objectName = category;
|
||||||
|
}
|
||||||
|
|
||||||
|
writeLog(msg, logType, objectName);
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void Logger::writeLog(const QString &msg, LogType type, const QString &objectName)
|
||||||
|
{
|
||||||
|
if (!logWorker) return;
|
||||||
|
|
||||||
|
static bool dbg {Application::isDebug()};
|
||||||
|
|
||||||
|
if (!dbg && ((type == LogType::LogDebug) || (type == LogType::LogInput)
|
||||||
|
|| (type == LogType::LogOutput))) return;
|
||||||
|
|
||||||
|
int typeInt { static_cast<int>(type) };
|
||||||
|
|
||||||
|
QMetaObject::invokeMethod(
|
||||||
|
logWorker,
|
||||||
|
"writeLog",
|
||||||
|
Qt::QueuedConnection,
|
||||||
|
Q_ARG(QString, msg),
|
||||||
|
Q_ARG(int, typeInt),
|
||||||
|
Q_ARG(QString, objectName)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
Logger::LogType Logger::stringToLogType(const QString &stringType)
|
||||||
|
{
|
||||||
|
if (stringType.contains("wrn", Qt::CaseInsensitive)
|
||||||
|
|| stringType.contains("warn", Qt::CaseInsensitive))
|
||||||
|
return LogType::LogWarning;
|
||||||
|
else if (stringType.contains("dbg", Qt::CaseInsensitive)
|
||||||
|
|| stringType.contains("debug", Qt::CaseInsensitive))
|
||||||
|
return LogType::LogDebug;
|
||||||
|
else if (stringType.contains("err", Qt::CaseInsensitive)
|
||||||
|
|| stringType.contains("critic", Qt::CaseInsensitive)
|
||||||
|
|| stringType.contains("fatal", Qt::CaseInsensitive))
|
||||||
|
return LogType::LogError;
|
||||||
|
else if (stringType.contains(">>>", Qt::CaseInsensitive)
|
||||||
|
|| stringType.contains("output", Qt::CaseInsensitive))
|
||||||
|
return LogType::LogOutput;
|
||||||
|
else if (stringType.contains("<<<", Qt::CaseInsensitive)
|
||||||
|
|| stringType.contains("input", Qt::CaseInsensitive))
|
||||||
|
return LogType::LogInput;
|
||||||
|
|
||||||
|
return LogType::LogInfo;
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
Logger::Logger(QObject *parent) : QObject{parent}
|
||||||
|
{
|
||||||
|
if ( !QMetaType::isRegistered( qMetaTypeId<Logger::LogType>() ) )
|
||||||
|
qRegisterMetaType<Logger::LogType>();
|
||||||
|
|
||||||
|
QCoreApplication *application = QCoreApplication::instance();
|
||||||
|
|
||||||
|
if (application) application->setProperty("loggerRun", true);
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
Logger::~Logger()
|
||||||
|
{
|
||||||
|
stop();
|
||||||
|
|
||||||
|
QCoreApplication *application = QCoreApplication::instance();
|
||||||
|
|
||||||
|
if (application) application->setProperty("loggerRun", false);
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
|
||||||
|
//==============================================================================
|
||||||
|
//
|
||||||
|
// LogWorker - internal class
|
||||||
|
//
|
||||||
|
//==============================================================================
|
||||||
|
LogWorker::LogWorker(const QString &logFilePath, QObject *parent) : QObject{parent}
|
||||||
|
{
|
||||||
|
file.setFileName(logFilePath);
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
LogWorker::~LogWorker()
|
||||||
|
{
|
||||||
|
stop();
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void LogWorker::start()
|
||||||
|
{
|
||||||
|
if (running) return;
|
||||||
|
|
||||||
|
if (!file.open(QIODevice::ReadWrite | QIODevice::Truncate)) {
|
||||||
|
|
||||||
|
qCritical() << "Не удалось открыть файл для записи: " << file.fileName();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
linesPosition = 0;
|
||||||
|
linesCounter = 0;
|
||||||
|
startTime = QDateTime::currentDateTime();
|
||||||
|
|
||||||
|
writeFirstLines();
|
||||||
|
writeLastLines();
|
||||||
|
|
||||||
|
timer = new QTimer(nullptr);
|
||||||
|
timer->setInterval(queueIntervalMs);
|
||||||
|
timer->setSingleShot(false);
|
||||||
|
|
||||||
|
connect(timer, &QTimer::timeout, this, &LogWorker::checkQueue);
|
||||||
|
|
||||||
|
timer->start();
|
||||||
|
running = true;
|
||||||
|
emit started();
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void LogWorker::stop()
|
||||||
|
{
|
||||||
|
if (!running) return;
|
||||||
|
|
||||||
|
QMutexLocker locker(&mutex);
|
||||||
|
running = false;
|
||||||
|
|
||||||
|
if (timer) {
|
||||||
|
|
||||||
|
timer->stop();
|
||||||
|
delete timer;
|
||||||
|
timer = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file.isOpen()) {
|
||||||
|
|
||||||
|
writeAllFromQueue();
|
||||||
|
writeLastLines();
|
||||||
|
|
||||||
|
file.flush();
|
||||||
|
file.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
emit stopped();
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void LogWorker::writeLog(const QString &msg, int type, const QString &objectName)
|
||||||
|
{
|
||||||
|
if (!running) return;
|
||||||
|
|
||||||
|
QMutexLocker lock(&mutex);
|
||||||
|
LogRecord rec {type, msg, objectName, QDateTime::currentDateTime()};
|
||||||
|
|
||||||
|
queue.enqueue(rec);
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void LogWorker::checkQueue()
|
||||||
|
{
|
||||||
|
if (!running) return;
|
||||||
|
if (!mutex.tryLock()) return;
|
||||||
|
|
||||||
|
writeAllFromQueue();
|
||||||
|
|
||||||
|
mutex.unlock();
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void LogWorker::writeFirstLines()
|
||||||
|
{
|
||||||
|
if (!file.isOpen()) return;
|
||||||
|
|
||||||
|
writeLine( tr("----- Начало %1 -")
|
||||||
|
.arg(startTime.toString("yyyy-MM-dd HH:mm:ss"))
|
||||||
|
.leftJustified(80,'-'),
|
||||||
|
-1);
|
||||||
|
|
||||||
|
QString runMode;
|
||||||
|
|
||||||
|
if (Application::isDebug()) {
|
||||||
|
|
||||||
|
runMode = "DEBUG";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Application::isPortable()) {
|
||||||
|
|
||||||
|
if (!runMode.isEmpty()) runMode += ", ";
|
||||||
|
runMode += "PORTABLE";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (runMode.isEmpty()) runMode = "NORMAL";
|
||||||
|
|
||||||
|
writeLine(tr("ПО: %1").arg(QCoreApplication::applicationName()), -1);
|
||||||
|
writeLine(tr("Версия: %1").arg(QCoreApplication::applicationVersion()), -1);
|
||||||
|
writeLine(tr("Разработчик: %1 %2")
|
||||||
|
.arg( QCoreApplication::organizationName(),
|
||||||
|
QCoreApplication::organizationDomain().isEmpty()
|
||||||
|
? QString()
|
||||||
|
: QString("(" + QCoreApplication::organizationDomain() + ")")
|
||||||
|
),
|
||||||
|
-1
|
||||||
|
);
|
||||||
|
writeLine(tr("Строка запуска: '%1'").arg( QCoreApplication::arguments().join(' ') ), -1);
|
||||||
|
writeLine(tr("Режим запуска: %1").arg(runMode), -1);
|
||||||
|
|
||||||
|
if (file.write(QByteArray(1,'\n')) == 1) {
|
||||||
|
|
||||||
|
++linesCounter;
|
||||||
|
++linesPosition;
|
||||||
|
}
|
||||||
|
|
||||||
|
file.flush();
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void LogWorker::writeLastLines()
|
||||||
|
{
|
||||||
|
if (!file.isOpen()) return;
|
||||||
|
|
||||||
|
if ((file.pos() != linesPosition) && !file.seek(linesPosition)) {
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
QDateTime endTime = QDateTime::currentDateTime();
|
||||||
|
qint64 n = endTime.toMSecsSinceEpoch() - startTime.toMSecsSinceEpoch();
|
||||||
|
qint64 hr = n / 3600000;
|
||||||
|
qint64 ms = n - 3600000 * hr;
|
||||||
|
qint64 min = ms / 60000;
|
||||||
|
ms = ms - 60000 * min;
|
||||||
|
qint64 sec = ms / 1000;
|
||||||
|
ms = ms - 1000 * sec;
|
||||||
|
|
||||||
|
file.write(QByteArray(1,'\n'));
|
||||||
|
|
||||||
|
writeLine(tr("Текущее состояние: %1")
|
||||||
|
.arg( running ? "в процессе работы" : "работа завершена" ),
|
||||||
|
-2
|
||||||
|
);
|
||||||
|
writeLine(tr("Общее время: %1 ч, %2 мин, %3 сек, %4 мсек")
|
||||||
|
.arg(hr).arg(min).arg(sec).arg(ms),
|
||||||
|
-2
|
||||||
|
);
|
||||||
|
|
||||||
|
writeLine(tr("Общее количество строк: %1")
|
||||||
|
.arg( linesCounter + 5 ),
|
||||||
|
-2
|
||||||
|
);
|
||||||
|
writeLine(tr("----- Окончание %1 -")
|
||||||
|
.arg( QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss") )
|
||||||
|
.leftJustified(80,'-'),
|
||||||
|
-2);
|
||||||
|
|
||||||
|
file.flush();
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void LogWorker::writeLine(const QString &msg, int type,
|
||||||
|
const QString &objectName, const QDateTime &dateTime)
|
||||||
|
{
|
||||||
|
QByteArray data {
|
||||||
|
QString(
|
||||||
|
dateTime.toString("[HH:mm:ss.zzz] ")
|
||||||
|
+ QString(type < 0 ? "[sys]" : Logger::logTypeToString(static_cast<quint8>(type)))
|
||||||
|
+ " "
|
||||||
|
+ QString(objectName.isEmpty() ? QString() : "{" + objectName + "} ")
|
||||||
|
+ msg
|
||||||
|
+ "\n"
|
||||||
|
).toUtf8()
|
||||||
|
};
|
||||||
|
|
||||||
|
qint64 bytesWrite {0};
|
||||||
|
int cnt {3};
|
||||||
|
|
||||||
|
while ((bytesWrite < data.size()) && (cnt > 0)) {
|
||||||
|
|
||||||
|
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
|
||||||
|
qint64 n = file.write(data.mid(bytesWrite));
|
||||||
|
#else
|
||||||
|
qint64 n = file.write(data.mid(static_cast<int>(bytesWrite)));
|
||||||
|
#endif
|
||||||
|
|
||||||
|
if (n > 0) {
|
||||||
|
|
||||||
|
bytesWrite += n;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
|
||||||
|
--cnt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type < -1) return;
|
||||||
|
|
||||||
|
linesPosition += bytesWrite;
|
||||||
|
|
||||||
|
if (bytesWrite == data.size()) ++linesCounter;
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
void LogWorker::writeAllFromQueue()
|
||||||
|
{
|
||||||
|
if (queue.isEmpty()) return;
|
||||||
|
|
||||||
|
if (!file.isOpen()) {
|
||||||
|
|
||||||
|
queue.clear();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((file.pos() != linesPosition) && !file.seek(linesPosition)) {
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (!queue.isEmpty()) {
|
||||||
|
|
||||||
|
LogRecord rec = queue.dequeue();
|
||||||
|
writeLine( rec.msg, rec.type, rec.objectName, rec.dateTime );
|
||||||
|
}
|
||||||
|
|
||||||
|
writeLastLines();
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
//
|
||||||
|
// FunctionLogger
|
||||||
|
//
|
||||||
|
//==============================================================================
|
||||||
|
FunctionLogger::FunctionLogger(const char *file,
|
||||||
|
int line,
|
||||||
|
const char *name,
|
||||||
|
const QLoggingCategory &category)
|
||||||
|
: functionName{name}
|
||||||
|
, logCategory{category.categoryName()}
|
||||||
|
{
|
||||||
|
id = counter++;
|
||||||
|
|
||||||
|
if (logCategory.isEmpty())
|
||||||
|
logCategory = "Function";
|
||||||
|
|
||||||
|
quint64 threadId = reinterpret_cast<quint64>(QThread::currentThreadId());
|
||||||
|
|
||||||
|
qDebug() << QString("{%1} ID: %2, Thread: %3, File: '%4', Line: %5, Entering function: %6")
|
||||||
|
.arg(logCategory)
|
||||||
|
.arg(id)
|
||||||
|
.arg(threadId)
|
||||||
|
.arg(file)
|
||||||
|
.arg(line)
|
||||||
|
.arg(functionName)
|
||||||
|
.toStdString().c_str();
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
FunctionLogger::~FunctionLogger()
|
||||||
|
{
|
||||||
|
qDebug() << QString("{%1} ID: %2, Exiting function: %3")
|
||||||
|
.arg(logCategory)
|
||||||
|
.arg(id)
|
||||||
|
.arg(functionName)
|
||||||
|
.toStdString().c_str();
|
||||||
|
}
|
||||||
|
//==============================================================================
|
||||||
|
|
Loading…
Reference in New Issue