emilk / loguru

A lightweight C++ logging library
The Unlicense
1.79k stars 260 forks source link

How I can catch and log errors or crashes in script #106

Closed djmv closed 5 years ago

djmv commented 5 years ago

My code is this and I want to see the crash on line *ptr = 42 with loguru. I want to log the crash and error in the line of code.

#define LOGURU_FILENAME_WIDTH  16
#define LOGURU_WITH_STREAMS     1
#define LOGURU_REDEFINE_ASSERT  1
#define LOGURU_USE_FMTLIB       0
#define LOGURU_WITH_FILEABS     0

#include "loguru.cpp"

int main(int argc, char* argv[])
{
    loguru::init(argc, argv);

    loguru::add_file("latest_readable.log", loguru::Truncate, loguru::Verbosity_INFO);
    loguru::add_file("everything.log", loguru::Append, loguru::Verbosity_MAX);
    LOG_F(INFO, "Hello log file!");
    int* ptr = nullptr;
    *ptr = 42;
    LOG_F(INFO, "goes to stderr, but not to file");
    return 0;
}

my output is this:

date       time         ( uptime  ) [ thread name/id ]                   file:line     v| 
2019-04-16 20:21:57.640 (   0.000s) [main thread     ]             loguru.cpp:591   INFO| arguments: ./test_log
2019-04-16 20:21:57.640 (   0.000s) [main thread     ]             loguru.cpp:594   INFO| Current dir: Documents/practices/c++/loguru
2019-04-16 20:21:57.640 (   0.000s) [main thread     ]             loguru.cpp:596   INFO| stderr verbosity: 0
2019-04-16 20:21:57.640 (   0.000s) [main thread     ]             loguru.cpp:597   INFO| -----------------------------------
2019-04-16 20:21:57.640 (   0.000s) [main thread     ]             loguru.cpp:755   INFO| Logging to 'everything.log', mode: 'a', verbosity: 9
2019-04-16 20:21:57.640 (   0.000s) [main thread     ]        loguru_test.cpp:7     INFO| Hello log file!
2019-04-16 20:21:57.640 (   0.000s) [main thread     ]             loguru.cpp:471   INFO| atexit

But doesn't catch the error.

It is my Makefile

CXXFLAGS= -fPIC -std=c++11 -O3 -march=native -DGXX_EXPERIMENTAL_CXX0X \
-L/usr/lib64/ \
-I/usr/lib/x86_64-linux-gnu/ \
-L/usr/lib/gcc/x86_64-linux-gnu/5/include/ \
-L/usr/local/lib/

LIB_LINK = -lm -lpthread -ldl -lstdc++

UNAME_M := $(shell uname -m)
ifeq ($(UNAME_M),armv7l)
    CXXFLAGS += -Wa,-mimplicit-it=thumb
endif

CXX = g++   
SRC_DIR = ./
OUT_DIR = ./build
BUILD_NAME = test_log

OBJECTS = loguru_test.o

compile: $(OBJECTS)
    $(CXX)  $(CXXFLAGS) $(OBJECTS) -o $(OUT_DIR)/$(BUILD_NAME) $(LIB_LINK)
    mv $(OBJECTS) $(OUT_DIR)/ 
loguru_test.o: $(SRC_DIR)/$ loguru_test.cpp
    $(CXX) $(CXXFLAGS) -c $< -o $@

clean:
    rm -rf $(OUT_DIR)/$(OBJECTS) $(OUT_DIR)/$(BUILD_NAME)

Please, help me.

emilk commented 5 years ago

Could be the compiler is smart enough to simply remove the assignment to *nullptr (it is, after all UB). Try without -O3 or a different compiler.