spdlog使用_医用耗材spd管理

spdlog使用_医用耗材spd管理目录Spdlog优点Example简单封装与使用使用中遇到的问题Spdlog优点只需包含头文件 无需依赖第三方库 支持跨平台 支持多线程 源码地址:https://github.com/g

spdlog使用_医用耗材spd管理"

目录

Spdlog优点

Example

简单封装与使用

使用中遇到的问题


 


Spdlog优点

  • 只需包含头文件
  • 无需依赖第三方库
  • 支持跨平台
  • 支持多线程

  • 源码地址:https://github.com/gabime/spdlog

Example

#define SPDLOG_TRACE_ON
#define SPDLOG_DEBUG_ON

#include "spdlog/spdlog.h"

#include <iostream>
#include <memory>

void async_example();
void syslog_example();
void android_example();
void user_defined_example();
void err_handler_example();

namespace spd = spdlog;
int main(int, char *[])
{
    try
    {
        // Console logger with color
        auto console = spd::stdout_color_mt("console");
        console->info("Welcome to spdlog!");
        console->error("Some error message with arg{}..", 1);

        // Formatting examples
        console->warn("Easy padding in numbers like {:08d}", 12);
        console->critical("Support for int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
        console->info("Support for floats {:03.2f}", 1.23456);
        console->info("Positional args are {1} {0}..", "too", "supported");
        console->info("{:<30}", "left aligned");

        spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");

        // Create basic file logger (not rotated)
        auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt");
        my_logger->info("Some log message");

        // Create a file rotating logger with 5mb size max and 3 rotated files
        auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
        for (int i = 0; i < 10; ++i)
        {
            rotating_logger->info("{} * {} equals {:>10}", i, i, i * i);
        }

        // Create a daily logger - a new file is created every day on 2:30am
        auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
        // trigger flush if the log severity is error or higher
        daily_logger->flush_on(spd::level::err);
        daily_logger->info(123.44);

        // Customize msg format for all messages
        spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v");
        console->info("This an info message with custom format");
        console->error("This an error message with custom format");

        // Runtime log levels
        spd::set_level(spd::level::info); // Set global log level to info
        console->debug("This message should not be displayed!");
        console->set_level(spd::level::debug); // Set specific logger's log level
        console->debug("This message should be displayed..");

        // Compile time log levels
        // define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON
        SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
        SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);

        // Asynchronous logging is very fast..
        // Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
        async_example();

        // syslog example. linux/osx only
        syslog_example();

        // android example. compile with NDK
        android_example();

        // Log user-defined types example
        user_defined_example();

        // Change default log error handler
        err_handler_example();

        // Apply a function on all registered loggers
        spd::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });

        // Release and close all loggers
        spdlog::drop_all();
		system("pause");
    }
    // Exceptions will only be thrown upon failed logger or sink construction (not during logging)
    catch (const spd::spdlog_ex &ex)
    {
        std::cout << "Log init failed: " << ex.what() << std::endl;
        return 1;
    }
}

void async_example()
{
    size_t q_size = 4096;
    spdlog::set_async_mode(q_size);
    auto async_file = spd::daily_logger_st("async_file_logger", "logs/async_log.txt");
    for (int i = 0; i < 100; ++i)
    {
        async_file->info("Async message #{}", i);
    }
}

// syslog example (linux/osx/freebsd)
void syslog_example()
{
#ifdef SPDLOG_ENABLE_SYSLOG
    std::string ident = "spdlog-example";
    auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
    syslog_logger->warn("This is warning that will end up in syslog.");
#endif
}

// Android example
void android_example()
{
#if defined(__ANDROID__)
    std::string tag = "spdlog-android";
    auto android_logger = spd::android_logger("android", tag);
    android_logger->critical("Use \"adb shell logcat\" to view this message.");
#endif
}

// user defined types logging by implementing operator<<
struct my_type
{
    int i;
    template<typename OStream>
    friend OStream &operator<<(OStream &os, const my_type &c)
    {
        return os << "[my_type i=" << c.i << "]";
    }
};

#include "spdlog/fmt/ostr.h" // must be included
void user_defined_example()
{
    spd::get("console")->info("user defined type: {}", my_type{14});
}

//
// custom error handler
//
void err_handler_example()
{
    // can be set globaly or per logger(logger->set_error_handler(..))
    spdlog::set_error_handler([](const std::string &msg) { std::cerr << "my err handler: " << msg << std::endl; });
    spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
}

简单封装与使用

参考1:https://www.cnblogs.com/LuckCoder/p/11171609.html

参考2:spdlog使用

  • SimLog.h
#pragma once
#include "spdlog\spdlog.h"
#include "spdlog\async_logger.h"
#include "spdlog\sinks\base_sink.h"

#ifdef _WIN32
//strrchr:查找字符在指定字符串从右面开始的第一次出现的位置,如果成功,返回该字符以及后面的字符,如果失败,返回NULL
//strcgr:查找字符在指定字符串首次出现的位置
#define __FILENAME__ (strrchr(__FILE__,'\\')?(strrchr(__FILE__,'\\')+1):__FILE__)
#else
#define __FILENAME__ (strrchr(__FILE__,'/')?(strrchr(__FILE__,'/')+1):__FILE__)
#endif //_WIN32


#ifndef SUFFIX
//在错误级别的日志后面追加文件名,函数名,行号
#define SUFFIX(msg) std::string(msg).append("  <")\
	.append(__FILENAME__).append("> <").append(__FUNCTION__)\
	.append("> <").append(std::to_string(__LINE__))\
	.append(">").c_str()
#endif //suffix

#define LTrace(msg,...)  SimLog::Instance().GetLogger()->trace(SUFFIX(msg),__VA_ARGS__)
#define LDebug(...)  SimLog::Instance().GetLogger()->debug(__VA_ARGS__)
#define LInfo(...)  SimLog::Instance().GetLogger()->info(__VA_ARGS__)
#define LWarn(...) SimLog::Instance().GetLogger()->warn(__VA_ARGS__)
#define LError(msg,...)  SimLog::Instance().GetLogger()->error(SUFFIX(msg),__VA_ARGS__)
#define LCritical(...)  SimLog::Instance().GetLogger()->critical(__VA_ARGS__)



class SimLog
{
private:
	std::shared_ptr<spdlog::logger> my_logger_;

public:	
	static SimLog &Instance();
	void InitSimLog(std::string logger_name, std::string file_name, int log_level = spdlog::level::trace);

	void SetLevel(int level = spdlog::level::trace);

	auto GetLogger()-> decltype(my_logger_)
	{
		return my_logger_;
	}
	
private:
	SimLog();
	~SimLog();
	SimLog(const SimLog &other) = delete;
	SimLog& operator=(const SimLog &other) = delete;

};

SimLog.cpp

#include "stdafx.h"
#include "SimLog.h"


SimLog& SimLog::Instance()
{
	static SimLog log;
	return log;
}
void SimLog::InitSimLog(std::string logger_name, std::string file_name, int log_level)
{
	//设置日志等级
	//spdlog::set_level(static_cast<spdlog::level::level_enum>(log_level));
	
	my_logger_ = spdlog::daily_logger_mt(logger_name, file_name, 0, 0);
	
	spdlog::set_pattern("[%Y-%m-%d %T][thread %t][%l]%v");   //设置logger的输出格式

	//当遇到错误级别以上的立刻刷新到日志
	my_logger_->flush_on(spdlog::level::info);

}


SimLog::SimLog()
{
}


SimLog::~SimLog()
{
	//spdlog::drop_all();
}
void SimLog::SetLevel(int level)
{
	spdlog::set_level(static_cast<spdlog::level::level_enum>(level));
}
  • 使用:将下载的include/spdlog添加到包含目录里,修改包含路径””<>
SimLog::Instance().InitSimLog("logTest", string(logs/log.txt), spdlog::level::info);
SimLog::Instance().SetLevel(m_setting.logLevel);
LError("error: code:{0},message:{1}", resCode, outRes);

使用中遇到的问题

  • 下载版本不同,写法不一样 ,根据实际下载的版本例子进行修改即可。比如
//2.x版本用法
spdlog::drop_all();
//1.x版本用法
spdlog::shutdown();
  • 析构spdlog::drop_all();可能会报错,注意析构顺序
  • 可以将日志等级写进配置文件,方便生产环境时定位问题
  • 多线程使用时使用spdlog::daily_logger_mt

今天的文章spdlog使用_医用耗材spd管理分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/78500.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注