I looked around and I couldn't find the answer to how exactly to do this. I am trying to use Pantheios for logging and I want to write to an external file (otherwise whats the point). I am following one of the examples provided but It doesn't seem to be making the log file anywhere. Here is the code:
Edit: Also pantheios_be_file_setFilePath is returning -4 (PANTHEIOS_INIT_RC_UNSPECIFIED_FAILURE) so thats.....not helpful
#include "stdafx.h"
#include <pantheios/pantheios.hpp>
#include <pantheios/implicit_link/core.h>
#include <pantheios/implicit_link/fe.simple.h>
#include <pantheios/implicit_link/be.WindowsConsole.h>
#include <pantheios/implicit_link/be.file.h>
#include <pantheios/frontends/fe.simple.h>
#include <pantheios/backends/bec.file.h>
#include <pantheios/inserters/args.hpp>
PANTHEIOS_EXTERN_C const PAN_CHAR_T PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING("LogTest");
int _tmain(int argc, _TCHAR* argv[])
{
try
{
pantheios_be_file_setFilePath(PANTHEIOS_LITERAL_STRING("testlogforme.log"), PANTHEIOS_BE_FILE_F_TRUNCATE, PANTHEIOS_BE_FILE_F_TRUNCATE, PANTHEIOS_BEID_ALL);
pantheios::log(pantheios::debug, "Entering main(", pantheios::args(argc,argv, pantheios::args::arg0FileOnly), ")");
pantheios::log_DEBUG("debug yo");
pantheios::log_INFORMATIONAL("informational fyi");
pantheios::log_NOTICE("notice me!");
pantheios::log_WARNING("warning!!");
pantheios::log_ERROR("error omg");
pantheios::log_CRITICAL("critical!!!");
pantheios::log_ALERT("alert mang");
pantheios::log_EMERGENCY("EMERGENCY!!!!!");
pantheios_be_file_setFilePath(NULL, PANTHEIOS_BEID_ALL);
system("pause");
return EXIT_SUCCESS;
}
catch(std::bad_alloc&)
{
pantheios::log_ALERT("out of memory");
}
catch(std::exception& x)
{
pantheios::log_CRITICAL("Exception: ", x);
}
catch(...)
{
pantheios::puts(pantheios::emergency, "Unexpected unknown error");
}
return EXIT_FAILURE;
}
Maybe I'm not calling a method or maybe its not being saved to a good location?
It turns out that some of the examples out there for pantheios are incorrect. You DO need to call pantheios_init() even if you are in C++. Here Is the example I got to work after deleting all my code and implementing an example that works.
// Headers for main()
#include <pantheios/pantheios.hpp>
#include <pantheios/backends/bec.file.h>
// Headers for implicit linking
#include <pantheios/implicit_link/core.h>
#include <pantheios/implicit_link/fe.simple.h>
#include <pantheios/implicit_link/be.file.h>
PANTHEIOS_EXTERN_C const char PANTHEIOS_FE_PROCESS_IDENTITY[] = "testLOL";
int main()
{
if(pantheios::pantheios_init() < 0)
{
return 1;
}
pantheios::log_NOTICE("log-1"); // save until log file set
pantheios_be_file_setFilePath("mylogfile.log"); // sets log file; write "log-1" stmt
pantheios::log_NOTICE("log-2"); // write "log-2" stmt
pantheios_be_file_setFilePath(NULL); // close "mylogfile"
pantheios::log_NOTICE("log-3"); // save until log file set
pantheios_be_file_setFilePath("mylogfile2.log"); // sets log file; write "log-3" stmt
pantheios::log_NOTICE("log-4"); // write "log-4" stmt
//system("pause");
return 0;
} // closes "mylogfile2" during program closedown
I found the example on a different post on stack overflow but like I said, the built in examples do not work.
Related
I downloaded and followed the example 1.
Moved to example 2 (Create stdout/stderr logger object) and got stuck. Actually I can run it as it is but if I change
spdlog::get("console") to spdlog::get("err_logger") it crashes.
Am I supposed to change it like that?
#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h"
void stdout_example()
{
// create color multi threaded logger
auto console = spdlog::stdout_color_mt("console");
auto err_logger = spdlog::stderr_color_mt("stderr");
spdlog::get("err_logger")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name)");
}
int main()
{
stdout_example();
return 0;
}
I also tried Basic file logger example:
#include <iostream>
#include "spdlog/sinks/basic_file_sink.h"
void basic_logfile_example()
{
try
{
auto logger = spdlog::basic_logger_mt("basic_logger", "logs/basic-log.txt");
}
catch (const spdlog::spdlog_ex &ex)
{
std::cout << "Log init failed: " << ex.what() << std::endl;
}
}
int main()
{
basic_logfile_example();
return 0;
}
And I see it creates basic-log.txt file but there is nothing on it.
Because you need to register err_logger logger first. There is no default err_logger as far as I know. spdlog::get() returns logger based on its registered name, not variable.
You need a code like this. Code is complex and you may not need all of it though:
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/sinks/rotating_file_sink.h"
void multi_sink_example2()
{
spdlog::init_thread_pool(8192, 1);
auto stdout_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt >();
auto rotating_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>("mylog.txt", 1024*1024*10, 3);
std::vector<spdlog::sink_ptr> sinks {stdout_sink, rotating_sink};
auto logger = std::make_shared<spdlog::async_logger>("err_logger", sinks.begin(), sinks.end(), spdlog::thread_pool(), spdlog::async_overflow_policy::block);
spdlog::register_logger(logger); //<-- this line registers logger for spdlog::get
}
and after this code, you can use spdlog::get("err_logger").
You can read about creating and registering loggers here.
I think spdlog::stderr_color_mt("stderr"); registers logger with name stderr so spdlog::get("stderr") may work, but have not tested myself.
I'm using perror:
perror("Error message:");
When the above is used it displays the message passed to the string followed by the actual error that occurred. This is a standard function, however I want to log this to a file, how to I get the actual error that goes with this so I can log it?
You can use the code below:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main() {
FILE* filePtr;
filePtr = fopen (logFilePath, "a");
//...
//some code
//...
if(critical_part){
fprintf(filePtr, "errno :%s Error in critical part - line 123\n",strerror(errno));
}
}
Can someone please tell me if this is correct way of using SysLogAppender of log4cplus ? I did not find a proper example for log4cplus. I need to send numerous logs to remote syslog server.
main.cpp
int main()
{
SysLogHelper syslogHelper;
int errCode = syslogHelper.initialize("172.16.72.239");
errCode = syslogHelper.sendLogstoSyslog("send testing log");
// I need to send numerous logs to syslog
}
syslog.cpp
#include <log4cplus/syslogappender.h>
#include <log4cplus/spi/loggingevent.h>
#include <log4cplus/logger.h>
class SysLogHelper
{
string hostname;
log4cplus::SysLogAppender *syslogAppender;
// is it necessary to create a pointer? I am not able to use log4cplus in a class without creating a pointer? Is there any other way?
log4cplus::spi::InternalLoggingEvent syslogLoggingEvent;
public:
SysLogHelper();
int initialize(string hostname);
int sendLogstoSyslog(string message);
};
SysLogHelper::SysLogHelper()
{
hostname = "";
syslogAppender = NULL;
}
int SysLogHelper::initialize(string hostname)
{
syslogAppender = new log4cplus::SysLogAppender("ident", hostname);
//I am not getting what is "ident" here? what input is expected?
return 0;
}
int SysLogHelper::sendLogstoSyslog(string message)
{
syslogLoggingEvent.setLoggingEvent(
log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("test")).getName(),
log4cplus::FATAL_LOG_LEVEL, LOG4CPLUS_TEXT(message),__FILE__,
__LINE__, "main");
syslogAppender->doAppend(syslogLoggingEvent);
//Is this correct method of sending logs to syslog?
return 0;
}
questions:
I am able to send logs to remote syslog using above code. But is this correct way to use log4cplus APIs? Questions are given in the form of comments in above code example.
Why do we need to use log4cplus::initializer? I am not able to import log4cplus/initializer.h in my code.
In my opinion the phylosophy at the base of Log4cplus library is that you can have in your application one or more logger and for each logger you can have one or more output, called "appender". Inside your application you have to manage with logger and you don't have care which appender are linked to the logger. This is clear, for example, if you use a property file to config and to tune your logger.
By the way here in the following I show what I have done to configure syslog inside my application in both cases:
configuring syslog appender inside the code:
#include <log4cplus/logger.h>
#include <log4cplus/fileappender.h>
#include <log4cplus/syslogappender.h>
#include <log4cplus/layout.h>
#include <log4cplus/ndc.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/property.h>
#include <log4cplus/loggingmacros.h>
#include <log4cplus/configurator.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/fileinfo.h>
#include <TCHAR.h>
using namespace std;
using namespace log4cplus;
using namespace log4cplus::helpers;
using namespace log4cplus;
int main()
{
log4cplus::initialize ();
Logger root = Logger::getRoot();
// log level INFO: you don't see TRACE and DEBUG on your syslogserver
root.setLogLevel(log4cplus::INFO_LOG_LEVEL);
SharedObjectPtr<Appender> ptrSys(
new SysLogAppender(
_T("mysyslog"),
_T("localhost"),
514,
_T("user"))) ;
root.addAppender(ptrSys);
for(int i=0; i<100; ++i)
{
LOG4CPLUS_TRACE(root, LOG4CPLUS_TEXT("Error log test")); //not visible
LOG4CPLUS_DEBUG(root, LOG4CPLUS_TEXT("Debug log test")); //not visible
LOG4CPLUS_INFO(root, LOG4CPLUS_TEXT("Info log test"));
LOG4CPLUS_WARN(root, LOG4CPLUS_TEXT("Warning log test"));
LOG4CPLUS_ERROR(root, LOG4CPLUS_TEXT("Error log test"));
}
log4cplus::Logger::shutdown();
return 0;
}
As I said the way, that I prefer, is by configuration file, called here configlog.properties
#include <log4cplus/logger.h>
#include <log4cplus/fileappender.h>
#include <log4cplus/syslogappender.h>
#include <log4cplus/layout.h>
#include <log4cplus/ndc.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/property.h>
#include <log4cplus/loggingmacros.h>
#include <log4cplus/configurator.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/fileinfo.h>
#include <TCHAR.h>
using namespace std;
using namespace log4cplus;
using namespace log4cplus::helpers;
using namespace log4cplus;
log4cplus::tstring getPropertiesFileArgument (std::wstring argv)
{
log4cplus::tstring file = LOG4CPLUS_C_STR_TO_TSTRING (argv);
log4cplus::helpers::FileInfo fi;
if (getFileInfo (&fi, file) == 0)
return file;
return LOG4CPLUS_TEXT ("log4cplus.properties");
}
int main()
{
log4cplus::initialize ();
PropertyConfigurator::doConfigure( getPropertiesFileArgument(_T("c:\\ConfigLog.properties")));
Logger root = Logger::getRoot();
for(int i=0; i<100; ++i) {
LOG4CPLUS_TRACE(root, LOG4CPLUS_TEXT("Error log test"));
LOG4CPLUS_DEBUG(root, LOG4CPLUS_TEXT("Debug log test"));
LOG4CPLUS_INFO(root, LOG4CPLUS_TEXT("Info log test"));
LOG4CPLUS_WARN(root, LOG4CPLUS_TEXT("Warning log test"));
LOG4CPLUS_ERROR(root, LOG4CPLUS_TEXT("Error log test"));
}
log4cplus::Logger::shutdown();
return 0;
}
the configlog.properties file is something like this
log4cplus.rootLogger=INFO, syslog
log4cplus.appender.syslog=log4cplus::SysLogAppender
log4cplus.appender.syslog.ident=syslog
log4cplus.appender.syslog.layout=log4cplus::PatternLayout
log4cplus.appender.syslog.layout.ConversionPattern=[%T] %-5p %b %x - %m%n
log4cplus.appender.syslog.host=localhost
log4cplus.appender.syslog.udp=true
log4cplus.appender.syslog.port=514
log4cplus.appender.syslog.facility=user
I hope to be not too in late and I hope this can be helpful for you
#include "IRSensor.h"
#include "Turret.h"
#include "StepperButtonController.h"
#include "LoadBottleButton.h"
LoadBottleButton go(A3,1000);
void setup()
{
Serial.begin(9600);
Serial.println("Port Open");
}
void loop()
{
if(go.Read())
{
go.Monitor();
}
}
Above is the Main code
#ifndef LoadBottleButton_cpp
#define LoadBottleButton_cpp
#include "Arduino.h"
#include "ScaleObject.h"
#include "LoadBottleButton.h"
#include "Turret.h"
#include "StepperButtonController.h"
ScaleObject* so;
Turret* tPointer;
LoadBottleButton::LoadBottleButton(int pin, int debounce):StepperButtonController(pin,debounce)
{
}
void LoadBottleButton::Monitor()
{
Serial.println("In Monitor");
while(tPointer->getTurret().BottleCenterState==false)
{
Serial.println("In Monitor While Loop");
tPointer->Start();
SETUP = true;
load = true;
unload = !so->getScale().Empty();
Serial.println(load);
Serial.println(unload);
Serial.println(!so->getScale().Empty());
if(unload)
{
unload=!so->getScale().Empty();
}
else if(load && !so->getScale().Empty())
{
load = !tPointer->BottleCentered();
}
if(!load && !unload && SETUP)
{
tPointer->Stop();
SETUP = false;
}
}
}
#endif
And above is the LoadBottleButtonClass.cpp file.
#ifndef Turret_cpp
#define Turret_cpp
//#include "HX711.h"
#include "Turret.h"
#include "Arduino.h"
#include "StepperButtonController.h"
#include "ScaleObject.h"
#include "IRSensor.h"
//StepperButtonController Clear(9,1000);
void StepTurret();
Turret turret(2,3,4,StepTurret);
void StepTurret()
{
turret.Step();
}
ScaleObject* tso;
IRSensor* irs;
Turret::Turret()
{
}
Turret Turret::getTurret()
{
return turret;
}
Turret::Turret(int en, int dir, int clk, void(*stepFunction)()):stepper2(en,dir,clk,stepFunction)
{
tso->getScale().tare();
tso->getScale().set_gain(128);
tso->getScale().set_scale(-3483.4);
}
void Turret::SeekBottleCenter()
{
Start();
while(irs->IRState()==1)
{
Serial.println("High");
Serial.println(irs->IRState());
}
while(irs->IRState()==0)
{
Serial.println("Low");
}
}
bool Turret::BottleCentered()
{
return turret.BottleCenterState;
}
void Turret::ClearFunction()
{
wt = tso->getScale().get_units();
while(wt>5)
{
Serial.println("Clearing");
wt = tso->getScale().get_units();
Rotate(20);
}
}
#endif
And above is the Turret.cpp file.
#ifndef IRSensor_cpp
#define IRSensor_cpp
#include "Arduino.h"
#include "IRSensor.h"
IRSensor i(5);
IRSensor::IRSensor(int pin)
{
IRSensorPin = pin;
pinMode(pin,INPUT);
}
int IRSensor::IRState()
{
return digitalRead(i.IRSensorPin);
}
#endif
And above is the IRSensor.cpp file. So essentially I press the go button declared in my main, that button calls monitor in the LoadBottleButton.cpp file, that method uses a turret point to get access to the Turret.cpp methods and a boolean named BottleCenterState. But the code only gets so far, it stops after printing "In" of the Serial.println("In Monitor") line. Why is that?
Don't count on the output to tell you where the error is. That serial print may have completed successfully and the message is buffered in an output stream waiting for a chance to be written to the serial port.
A much more likely cause of the crash is the line below the serial print.
Serial.println("In Monitor");
while(tPointer->getTurret().BottleCenterState==false)
tPointer is used and I don't see anywhere in the provided code it is assigned a valid, dereferencable pointer. Dereferencing an undefined pointer results in undefined behaviour, and in this case probably a crash. Even if it isn't the crash you are seeing, this is almost certainly wrong.
How to fix it?
From the code provided it doesn't look like tpointer needs to be a pointer at all.
Turret turret;
May be all you need. Allocating turret statically eliminates the possibility of pointer and memory management bugs and reduces the chance of leaks.
Otherwise,
Turret* tPointer = new Turret();
But this leaves you with the problem of how and when do you delete tPointer;.
Check that your string doesn't contain a NULL character. This will terminate the string abruptly.
I am running the code below and I cannot redirect to a file. The file is made, but nothing is put into it. If I remove the last dup2(saveout,1) statement, I can create and write into the file, but I cannot get back to the terminal, which is important. As soon as I put the dup2(saveout,1) back in my code, the redirection stops working, but I can get back to the terminal. I do not understand why this is happening. I would like to redirect and go back into the terminal.
main.cpp
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
using namespace std;
void printmessage() {
printf("this is the message\n");
}
int main(int argc, char** argv) {
int saveout;
int fd;
saveout = dup(1);
for (int i = 0; i < 10; i++) {
fd = creat("/home/carl/example.txt",O_CREAT|O_APPEND);
dup2(fd, 1);
close(fd);
printf("Testing the message");
printmessage();
dup2(saveout,1);
close(saveout);
}
return 0;
}
This is a file rights issue, you should read the man pages of the functions you are using.
creat() takes as first argument the filename, and as second the file creation rights, not its opening mode.
The creat() functions is a simple open() call, with some particular flags, so that you'll just have to set up the rights.
if you want to open your file, and create it if he doesn't exists, use
open(filename, O_CREAT | O_RDWR | O_APPEND, 0600) for example, or
creat(filename, 0600),
which is mostly its equivalent, but you wont be able to append text, as "creat() is equivalent to open() with flags equal to O_CREAT | O_WRONLY | O_TRUNC"
The second dup2(saveout,1); will fail because you closed saveout.
printf is buffered by default. (line-by-line for output to a tty, perhaps differently for output to something else). Before both your calls to dup2(..., 1), you should flush with fflush:
fflush(stdout);