apply 'with<>' to a skipper parser to get context - boost

My first version of this question was rich with misunderstandings. My answer below suits my needs. But I kept at it to understand what could be done with with<>. What I get is that it intended to inject context into a parser. Then the parser is called from with_directive::parse (in x3's with.hpp) In the following code, that is just what happens.
#include <boost/spirit/home/x3.hpp>
using namespace boost::spirit::x3;
struct eol_parser_cnt : parser<eol_parser_cnt>
{
struct context {
int line = 0;
std::string::iterator iter_pos;
};
template <typename Iterator, typename Context, typename Attribute>
bool parse(Iterator& first, Iterator const& last
, Context const& context, unused_type, Attribute& attr) const
{
//std::cout << context.line;
auto& ctx = context;
return boost::spirit::x3::parse(first, last, lit(' ') | (lit("//") >> *(char_ - eol) >> eol));
}
};
const auto& our_skipper = eol_parser_cnt{};
eol_parser_cnt::context lines;
auto with_skipper = with<eol_parser_cnt::context>(lines)[our_skipper];
int main()
{
std::string str("12 word");
auto first = str.begin();
phrase_parse(first, str.end(), int_ >> *char_("a-z"), with_skipper);
}
Putting a break point in eol_parser_cnt::parse and I see it working. The debugger consistently shows the context is there and that it is the structure of eol_parser_cnt::context. I can change the value of line in the debugger and the next hit shows that value, it is a real object. But, try to uncomment the line std::cout << context.line; and the compiler complains that is it an unused_type. So, I just don't get it.
test.cpp(15,30): error C2039: 'line': is not a member of 'boost::spirit::x3::context<ID,T,Context>'
with
[
ID=eol_parser_cnt::context,
T=eol_parser_cnt::context,
Context=boost::spirit::x3::unused_type
]
F:\cpp\boost_1_76_0\boost\spirit\home\x3\support\context.hpp(18): message : see declaration of 'boost::spirit::x3::context<ID,T,Context>'
with
[
ID=eol_parser_cnt::context,
T=eol_parser_cnt::context,
Context=boost::spirit::x3::unused_type
]
F:\cpp\boost_1_76_0\boost\spirit\home\x3\directive\with.hpp(62): message : see reference to function template instantiation 'bool eol_parser_cnt::parse<Iterator,boost::spirit::x3::context<ID,T,Context>,Attribute>(Iterator &,const Iterator &,const boost::spirit::x3::context<ID,T,Context> &,boost::spirit::x3::unused_type,Attribute &) const' being compiled
with
[
Iterator=std::_String_iterator<std::_String_val<std::_Simple_types<char>>>,
ID=eol_parser_cnt::context,
T=eol_parser_cnt::context,
Context=boost::spirit::x3::unused_type,
Attribute=const boost::spirit::x3::unused_type
]

Well, it took a while but I was going to understand this. I re-read C++ Template Metaprogramming seriously this time. Then looking at the x3 code I finally understood that with<> is just another parser wrapper. It is interesting to debug an optimized build and see just how much code disappears. VS shows all the disappeared stuff on the stack as inlined and what was 9 layers of parser calls becomes 2 into the likes of with_error_handling::on_error. Everything from my call to parse_rhs_main (in rule.hpp, line 232), is gone.
So because with<> is just another parser wrapper and if the skipper is wrapped, the context is only avaliable to the skipper. But no big deal as the skipper is in the context of the main parser. The difference is that in the skipper object a get<skipper_eol_cnt>(context) returns a reference to the skipper_eol_cnt::context{}. Whereas in the main parser we have to us get<skipper_tag>(context) and this returns the with<> parser object. val is a member of that parser, the reference to the skipper_eol_cnt::context{}. So get<skipper_tag>(context).val retrieves the context we are looking for.
So here it is, using with<> applied to a skipper.
#include<iostream>
#include <iomanip>
#include <vector>
//#define BOOST_SPIRIT_X3_DEBUG
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/adapted.hpp>
using namespace boost::spirit::x3;
struct skipper_eol_cnt : parser<skipper_eol_cnt>
{
struct context {
int line = 1;
std::string::iterator iter_pos;
};
template <typename Iterator, typename Context, typename Attribute>
bool parse(Iterator& first, Iterator const& last
, Context const& context, unused_type, Attribute& attr) const
{
const char* start_cmt = "/*";
const char* end_cmt = "*/";
if (first == last)
return false;
bool matched = false;
//here we are getting from the 'with<>' wrapper
auto& ctx = get<skipper_eol_cnt>(context);
//skip: space | '//comment'
boost::spirit::x3::parse(first, last, lit(' ') | (lit("//") >> *(char_ - eol)));//eol counted below
//skip: '/*comment*/'
if (detail::string_parse(start_cmt, first, last, unused, case_compare<Iterator>())) {
for (; first != last; ++first) {
if (detail::string_parse(end_cmt, first, last, unused, case_compare<Iterator>()))
break;
if (*first == '\n')
++ctx.line, ctx.iter_pos = first;
}
}
Iterator iter = first;
for (; iter != last && (*iter == '\r' || *iter == '\n'); ++iter) {
matched = true;
if (*iter == '\n') // LF
++ctx.line, ctx.iter_pos = iter;
}
//{static int pos = 0; if (pos < ctx.line) { pos = ctx.line; std::cout << pos << std::endl; }}
if (matched) first = iter;
return matched;
}
};
auto const& skip_eol_cnt = skipper_eol_cnt{};
struct with_error_handling {
template<typename It, typename Ctx>
error_handler_result on_error(It f, It l, expectation_failure<It> const& ef, Ctx const& ctx) const {
It erit = f + std::distance(f, ef.where());
//here we are getting the wrapped skipper so need the 'with<>.val'
const auto& sctx = get<skipper_tag>(ctx).val;
It bit = erit;
for (; *bit != '\n'/* && bit != f*/; --bit)
;
It eit = erit;
for (; *eit != '\n' && eit != l; ++eit)
;
int str_pos = erit - bit - 1;
std::ostringstream oss;
oss << "Expecting " << ef.which() << "\n at line: " << sctx.line
<< "\n\t" << std::string(bit + 1, eit)
<< "\n\t" << std::setw(str_pos) << std::setfill('-') << "" << "^";
get<with_error_handling>(ctx).push_back(oss.str());;
return error_handler_result::fail;
}
};
//attr sections
struct section_type {
std::string name;
int line;
std::string::iterator iter_pos;
};
BOOST_FUSION_ADAPT_STRUCT(section_type, name)
using sections_type = std::vector<section_type>;
struct parser_find_sections : parser<parser_find_sections> {
template<typename Iterator, typename Context, typename RContext, typename Attribute>
bool parse(Iterator& first, Iterator const& last, Context const& context, RContext const& rcontext, Attribute& section) const {
const auto& sssctx = get<skipper_eol_cnt>(context); //now here this doesn't work, unused_type, but
const auto& sctx = get<skipper_tag>(context).val;
auto to_line = [&sctx, first](auto& ctx) {
_attr(ctx).line = sctx.line;
//_attr(ctx).iter_pos = first; // this one will get at 'section color(x,x)'
_attr(ctx).iter_pos = _where(ctx).begin(); // this one is '(x,x)'
};
static_assert(BOOST_VERSION / 100 % 1000 >= 77);
////NOTE!!! if you have a boost version of less than 1.77, x3::seek will fail here
////quick fix, copy from: https://github.com/boostorg/spirit/blob/boost-1.78.0/include/boost/spirit/home/x3/directive/seek.hpp
////and paste to your boost file...
return phrase_parse(first, last, *(seek["section"] >> (*alpha)[to_line]), get<skipper_tag>(context), section);
}
};
auto const parse_section = rule<with_error_handling, std::pair<int, int>>("the_sec_parser") = [] {
return '(' > int_ > ',' > int_ > ')';
}();
template<typename T>
std::ostream& operator << (std::ostream& os, std::pair<T, T>& t) {
return os << t.first << ',' << t.second;
}
//errors
std::vector<std::string> errors;
auto with_errors = with<with_error_handling>(errors)[parse_section];
auto test_section = [](auto& content, auto& section) {
//attr
std::pair<int, int> attr;
skipper_eol_cnt::context ctx{ section.line, section.iter_pos };
auto with_skip_cnt = with< skipper_eol_cnt>(ctx)[skip_eol_cnt];
auto first(section.iter_pos);
return std::tuple(phrase_parse(first, content.end(), with_errors, with_skip_cnt, attr), attr);
};
int main() {
std::string str(R"(//line 1
section red(5, 6)
section green( 7, 8) //line 3
section blue(9, 10) //no error
/*comment
bunch of lines of stuff....
*/ section white(11, a 12) //error on line 7
section black( 13,14)
)");
//get the list of sections
auto with_skip_cnt = with<skipper_eol_cnt>(skipper_eol_cnt::context{})[skip_eol_cnt];
sections_type secs;
auto first(str.begin());
phrase_parse(first, str.end(), parser_find_sections(), with_skip_cnt, secs);
for (auto& item : secs)
std::cout << item.name << "\t at line: " << item.line << std::endl;
//section 'blue', at 2, has no error
auto [r, attr] = test_section(str, secs.at(2));
if (r)
std::cout << "\nthe " << secs.at(2).name << " hase vals: " << attr << "\n\n";
//section 'white', at 3, has an error
test_section(str, secs.at(3));
if (errors.size())
std::cout << errors.front() << std::endl;
return 0;
}

Related

libzip: zip_name_locate() fails on specific filename, even trying all possible encoding combinations

I am trying to build a "failsafe" layer on top of libzip but libzip is giving me some trouble here.
First I add a file to my (empty) archive with zip_file_add(...). This has 3 possible user-defined encodings available. Then I try to locate the name with zip_name_locate(...) which also has 3 possible user-defined encodings available.
This mcve checks all possible encoding combinations and all of them fail for the specific filename x%²»Ã-ØÑ–6¨wx.txt. When using a more conventional file.txt filename, zip_name_locate() succeeds every time.
#include <zip.h>
#include <include/libzip.h>//<.pragmas to include the .lib's...
#include <iostream>
#include <vector>
#include <utility>
/*
'zip_file_add' possible encodings:
ZIP_FL_ENC_GUESS
ZIP_FL_ENC_UTF_8
ZIP_FL_ENC_CP437
'zip_name_locate' possible encodings:
ZIP_FL_ENC_RAW
ZIP_FL_ENC_GUESS
ZIP_FL_ENC_STRICT
*/
/*
build encoding pairs (trying all possibilities)
*/
std::vector<std::pair<unsigned, unsigned>>
encoding_pairs{
{ ZIP_FL_ENC_GUESS, ZIP_FL_ENC_RAW },
{ ZIP_FL_ENC_UTF_8, ZIP_FL_ENC_RAW },
{ ZIP_FL_ENC_CP437, ZIP_FL_ENC_RAW },
{ ZIP_FL_ENC_GUESS, ZIP_FL_ENC_GUESS },
{ ZIP_FL_ENC_UTF_8, ZIP_FL_ENC_GUESS },
{ ZIP_FL_ENC_CP437, ZIP_FL_ENC_GUESS },
{ ZIP_FL_ENC_GUESS, ZIP_FL_ENC_STRICT },
{ ZIP_FL_ENC_UTF_8, ZIP_FL_ENC_STRICT },
{ ZIP_FL_ENC_CP437, ZIP_FL_ENC_STRICT },
};
int main(int argc, char** argv) {
const char* file_buf = "hello world";
#if 0
const char* file_name = "file.txt";
#else
const char* file_name = "x%²»Ã-ØÑ–6¨wx.txt";
#endif
zip_error_t ze;
zip_error_init(&ze);
{
zip_source_t* zs = zip_source_buffer_create(nullptr, 0, 1, &ze);
if (zs == NULL)
return -1;
zip_t* z = zip_open_from_source(zs, ZIP_CHECKCONS, &ze);
if (z == NULL)
return -1;
{
zip_source_t* s = zip_source_buffer(z, file_buf, strlen(file_buf), 0);//0 = don't let libzip auto-free the const char* buffer on the stack
if (s == NULL)
return -1;
for (size_t ep = 0; ep < encoding_pairs.size(); ep++) {
std::cout << "ep = " << ep << std::endl;
zip_uint64_t index;
if ((index = zip_file_add(z, file_name, s, encoding_pairs[ep].first)) == -1) {
std::cout << "could not zip_file_add() with encoding " << encoding_pairs[ep].first << std::endl;
continue;
}
if (zip_name_locate(z, file_name, encoding_pairs[ep].second) == -1) {
std::cout << "the name '" << file_name << "' could not be located." << std::endl;
std::cout << " encoding pair: " << encoding_pairs[ep].first << " <-> " << encoding_pairs[ep].second << std::endl;
}
else {
std::cout << "the name was located." << std::endl;
}
if (zip_delete(z, index) == -1)
return -1;
}
}
zip_close(z);
}
zip_error_fini(&ze);
return 0;
}
I don't understand what I might be doing wrong here or if libzip just can't even resolve such a name.
If it can't then what would be the criteria on names to avoid ?
It turns out the problem was the encoding of my source file itself. It was ANSI - So I converted it to UTF8 and it solved the issue.
What I still don't understand is why libzip can't zip_name_locate() a name from an input c-string that is exactly the same as the input c-string used in zip_file_add() (whatever the source file encoding might be). "Lost in translation" perhaps ?
(Special thanks to Thomas Klausner for helping me find the issue).

c++ : unordered map with pair of string_viewes

Here is a code snippet I have :
struct PairHasher {
size_t operator()(const std::pair<std::string_view, std::string_view>& stop_stop) const {
return hasher(stop_stop.first) + 37*hasher(stop_stop.second);
}
std::hash<std::string_view> hasher;
};
BOOST_FIXTURE_TEST_CASE(unordered_map_string_view_pair_must_be_ok, TestCaseStartStopMessager)
{
const std::vector<std::string> from_stops = {"from_0", "from_1", "from_2"};
const std::vector<std::string> to_stops = {"to_0", "to_1", "to_2"};
std::unordered_map<std::pair<std::string_view, std::string_view>, std::int32_t, TransportCatalogue::PairHasher> distance_between_stops;
for ( std::size_t idx = 0; idx < from_stops.size(); ++idx) {
std::cout << from_stops[idx] << " : " << to_stops[idx] << std::endl;
distance_between_stops[std::pair(from_stops[idx], to_stops[idx])] = idx;
}
std::cout << "MAP CONTENT :" << std::endl;
for (auto const& x : distance_between_stops)
{
std::cout << x.first.first << " : " << x.first.second << std::endl;
}
}
I expect to see 3 pairs inside the container, but there is only 1 concerning to the output :
MAP CONTENT :
from_2 : to_2
So, where are two more pair lost? What am I doing wrong?
Moving my comment to an answer.
This is pretty sneaky. I noticed in Compiler Explorer that changing:
distance_between_stops[std::pair(from_stops[idx], to_stops[idx])] = idx;
to
distance_between_stops[std::pair(std::string_view{from_stops[idx]}, std::string_view{to_stops[idx]})] = idx;
fixes the bug. This hints that the problem lies in some implicit string -> string_view conversion. And indeed that is the case, but it is hidden behind one extra layer.
std::pair(from_stops[idx], to_stops[idx]) creates a std::pair<std::string, std::string>, but distance_between_stops requires a std::pair<std::string_view, std::string_view>. When we insert values into the map, this conversion happens implicitly via overload #5 here:
template <class U1, class U2>
constexpr pair(pair<U1, U2>&& p);
Initializes first with std::forward<U1>(p.first) and second with std::forward<U2>(p.second).
This constructor participates in overload resolution if and only if std::is_constructible_v<first_type, U1&&> and std::is_constructible_v<second_type, U2&&> are both true.
This constructor is explicit if and only if std::is_convertible_v<U1&&, first_type> is false or std::is_convertible_v<U2&&, second_type> is false.
(For reference, std::is_constructible_v<std::string_view, std::string&&> and std::is_convertible_v<std::string&&, std::string_view> are both true, so we know this overload is viable and implicit.)
See the problem yet? When we use the map's operator[], it has to do an implicit conversion to create a key with the proper type. This implicit conversion constructs a pair of string_views that are viewing the temporary memory from the local pair of strings, not the underlying strings in the vector. In other words, it is conceptually similar to:
std::string_view foo(const std::string& s) {
std::string temp = s + " foo";
return temp;
}
int main() {
std::string_view sv = foo("hello");
std::cout << sv << "\n";
}
Clang emits a warning for this small example, but not OP's full example, which is unfortunate:
warning: address of stack memory associated with local variable 'temp' returned [-Wreturn-stack-address]
return temp;
^~~~

Idiomatic complete matching with post skipping

What is the most idiomatic way to do post-skipping? More specific I want to ensure there is no "non-skippable" (garbage) characters in my input after matching my top rule.
auto const blankOrComment
= ascii::space
| x3::lexeme ['#' >> *(x3::char_ - x3::eol) >> -x3::eol ]
;
auto const program = rule<AstProgram>("program")
= *(as<AstDefinition> (definition > ";"))
;
auto const programEntry = x3::skip(blankOrComment) [program];
One idea, I consider quite ugly was to do a separate parse call for the blankOrComment afterwards, if the main iterator position is not the end iterator. The current better idea I have is to change the root rule:
auto const programEntry = x3::skip(blankOrComment) [program >> x3::omit[*blankOrComment]];
Is there a more idiomatic way?
The simplest hack is to tack on >> eps: Live On Coliru
Note I'd strive to make the skipper more self-descriptive:
auto const skipper
= space
| '#' >> *(char_ - eol) >> (eol|eoi)
;
Likewise you can make that postskip hack more self-descriptive:
auto const post_skip = eps;
auto const program = "program" >> post_skip;
Live On Coliru
#include <iostream>
#define BOOST_SPIRIT_X3_DEBUG
#include <boost/spirit/home/x3.hpp>
namespace Parser {
namespace x3 = boost::spirit::x3;
namespace rules {
using namespace x3;
auto const skipper
= space
| '#' >> *(char_ - eol) >> (eol|eoi)
;
auto const post_skip = eps;
auto const program = "program" >> post_skip;
}
auto const programEntry = x3::skip(rules::skipper) [rules::program];
}
int main() {
using It = std::string::const_iterator;
for (std::string const input : {
"",
" program ",
"#hello\n program # comment\n",
}) {
It f = input.begin(), l = input.end();
if(parse(f, l, Parser::programEntry)) {
std::cout << "Parse success\n";
} else {
std::cout << "Parse failed\n";
}
std::cout << "Remaining: '" << std::string(f,l) << "'\n";
}
}
Prints
Parse failed
Remaining: ''
Parse success
Remaining: ''
Parse success
Remaining: ''

File Isn't Deleting

I have a code that finds files that are less than 20 seconds old. It's finding them, but I can't get them deleted. I am using remove(). I've tried using remove with wildcards but no luck. It has to be something with the syntax. Any help is appreciated. Thank you.
using namespace std;
typedef vector<WIN32_FIND_DATA> tFoundFilesVector;
std::wstring LastWriteTime;
int getFileList(const char * filespec, tFoundFilesVector &foundFiles)
{
WIN32_FIND_DATA findData;
HANDLE h;
int validResult=true;
int numFoundFiles = 0;
h = FindFirstFile((LPCSTR)filespec, &findData);
if (h == INVALID_HANDLE_VALUE)
return 0;
while (validResult)
{
numFoundFiles++;
foundFiles.push_back(findData);
validResult = FindNextFile(h, &findData);
}
return numFoundFiles;
}
void showFileAge(tFoundFilesVector &fileList)
{
unsigned _int64 fileTime, curTime, age;
tFoundFilesVector::iterator iter;
FILETIME ftNow;
CoFileTimeNow(&ftNow);
curTime = ((_int64) ftNow.dwHighDateTime << 32) + ftNow.dwLowDateTime;
for (iter=fileList.begin(); iter<fileList.end(); iter++)
{
fileTime = ((_int64)iter->ftLastWriteTime.dwHighDateTime << 32) + iter- >ftLastWriteTime.dwLowDateTime;
age = curTime - fileTime;
if (age <= (_int64)200000000UL)
{
wcout << " Delete: '" <<endl;
wcout << "FILE: '" << iter->cFileName << "', AGE: " << (_int64)age/10000000UL << " seconds" << endl;
remove("C:\\mapper\\iter->cFileName");
}
else
{
//wcout << " Quit: '" <<endl;
//return;
}
}
}
int main()
{
string fileSpec = "*.*";
tFoundFilesVector foundFiles;
tFoundFilesVector::iterator iter;
int foundCount = 0;
getFileList("c:\\Mapper\\*.txt", foundFiles);
getFileList("c:\\Mapper\\*.jpg", foundFiles);
foundCount = foundFiles.size();
if (foundCount)
{
wcout << "Found "<<foundCount<<" matching files.\n";
showFileAge(foundFiles);
}
system("pause");
return 0;
}
You need to concatenate the strings "C:\mapper\" with whatever is in iter->cFileName. The most simple way of doing that would be to use the std::string class.
The result would look something like this:
remove(string("c:\\mapper\\").append(string(iter->cFileName)).c_str());
This assumes you do not use unicode encoding of your strings, otherwise you need to use std::wstring. To use these classes you will also need to include
#include <string>
in the top of your file.

how to customize "TimeStamp" format of Boost.Log

I want to get year-month-day hour:minute:second.fraction(2 digits), if I use "%Y-%m-%d %H:%M:%S.%f", I got almost what I want exception for the fraction( last part ) of seconds, it's showing 6 digits on my Windows XP, I don't know how to get 2 digits only, any idea?
I'm using this
namespace boost
{
BOOST_LOG_OPEN_NAMESPACE
namespace attributes
{
template <typename date_time_type>
void format_time_ms( std::ostringstream& formatter, const date_time_type& date_time)
{
auto time = date_time.time_of_day();
using namespace std;
formatter
<< setfill( '0') << setw( 2) << time.hours() << ':'
<< setfill( '0') << setw( 2) << time.minutes() << ':'
<< setfill( '0') << setw( 2) << time.seconds() << ','
<< setfill( '0') << setw( 3) << time.fractional_seconds() / 1000;
}
template <typename date_time_type>
std::string format_time_ms( const date_time_type& date_time)
{
std::ostringstream formatter;
format_time_ms( formatter, date_time);
auto time = date_time.time_of_day();
return formatter.str();
}
template <typename date_time_type>
std::string format_date_time_ms( const date_time_type& date_time, const char date_time_sep = ' ')
{
using namespace std;
ostringstream formatter;
auto date = date_time.date();
formatter
<< date.year() << '-'
<< setfill( '0') << setw( 2) << int( date.month()) << '-'
<< setfill( '0') << setw( 2) << date.day() << date_time_sep;
format_time_ms( formatter, date_time);
return formatter.str();
}
template <typename date_time_type, const char date_time_sep = ' '>
struct date_time_ms_formatter
{
std::string operator () ( const date_time_type& date_time) { return format_date_time_ms( date_time, date_time_sep); }
};
struct time_ms_formatter
{
template <typename date_time_type>
std::string operator () ( const date_time_type& date_time) { return format_time_ms( date_time); }
};
template <typename time_type>
struct local_clock_source
{
time_type operator () () const
{
return date_time::microsec_clock<time_type>::local_time();
}
};
template <typename time_type>
struct universal_clock_source
{
time_type operator () () const
{
return date_time::microsec_clock<time_type>::universal_time();
}
};
template <typename time_type, typename clock_source_type, typename formater_type>
class custom_clock: public attribute
{
public:
class impl: public attribute::impl
{
public:
attribute_value get_value()
{
auto str = formater_type()( clock_source_type()());
return make_attribute_value( str);
}
};
custom_clock(): attribute( new impl()) {}
explicit custom_clock( const cast_source& source): attribute( source.as<impl>()) {}
};
typedef custom_clock<boost::posix_time::ptime, local_clock_source<boost::posix_time::ptime>, date_time_ms_formatter<boost::posix_time::ptime, '\t'> > local_date_time_ms_clock;
typedef custom_clock<boost::posix_time::ptime, universal_clock_source<boost::posix_time::ptime>, date_time_ms_formatter<boost::posix_time::ptime, '\t'> > universal_date_time_ms_clock;
typedef custom_clock<boost::posix_time::ptime, local_clock_source<boost::posix_time::ptime>, time_ms_formatter> local_time_ms_clock;
typedef custom_clock<boost::posix_time::ptime, universal_clock_source<boost::posix_time::ptime>, time_ms_formatter> universal_time_ms_clock;
}
BOOST_LOG_CLOSE_NAMESPACE // namespace log
}
initialized as
BOOST_LOG_ATTRIBUTE_KEYWORD( dateTimeStamp, "DateTime", boost::posix_time::ptime)
BOOST_LOG_ATTRIBUTE_KEYWORD( timeStamp, "Time", boost::posix_time::ptime)
core->add_global_attribute( dateTimeStamp.get_name(), attrs::local_date_time_ms_clock());
core->add_global_attribute( timeStamp.get_name(), attrs::local_time_ms_clock());
and used as
expr::stream << expr::attr<std::string>( dateTimeStamp.get_name())
expr::stream << expr::attr<std::string>( timeStamp.get_name())
Boost.DateTime (upon which Boost.Log relies) doesn't seem to support specialized fractional seconds formatting, so the only way to do that would be to write your own custom attribute formatter, or (the easier, but less nice way) to slightly modify your formatting code.
Instead of something like this:
backend->set_formatter
(
fmt::stream <<
fmt::date_time<boost::posix_time::ptime>
("TimeStamp", keywords::format = "%Y-%m-%d %H:%M:%S.%f"));
backend->set_formatter
(
fmt::stream <<
fmt::date_time<boost::posix_time::ptime>
("TimeStamp", keywords::format = %Y-%m-%d %H:%M:%S.") <<
(fmt::format("%.2s") % fmt::date_time<boost::posix_time::ptime>("%f"))
);
I haven't tested it myself, but I believe it should work: the first fmt::date_time() will return the timestamp without the fractional seconds, while the second fmt::date_time() will return just the fractional seconds, which will be cut to two digits by the fmt::format().
We addressed it with this class:
class TimeStamp : public boost::log::attributes::local_clock {
public:
typedef boost::log::attribute_value attribute_type;
typedef boost::log::attributes::local_time_traits TimeTraitsT;
typedef TimeTraitsT::time_type time_type;
typedef boost::log::attributes::basic_attribute_value< std::string > result_value;
public:
boost::shared_ptr< attribute_type > get_value() {
time_type posix_time = boost::date_time::microsec_clock< time_type >::universal_time();
time_type::time_duration_type time = posix_time.time_of_day();
time_type::date_type date = posix_time.date();
std::stringstream formatter;
formatter
<< date.year() << "-"
<< std::setfill('0') << std::setw(2) << int(date.month()) << "-"
<< std::setfill('0') << std::setw(2) << date.day() << " "
<< std::setfill('0') << std::setw(2) << boost::date_time::absolute_value(time.hours()) << ":"
<< std::setfill('0') << std::setw(2) << boost::date_time::absolute_value(time.minutes()) << ":"
<< std::setfill('0') << std::setw(2) << boost::date_time::absolute_value(time.seconds()) << ","
<< std::setfill('0') << std::setw(2) << boost::date_time::absolute_value(time.fractional_seconds()) / 1000
;
return boost::make_shared< result_value >(formatter.str());
}
};
Initialized like this:
boost::log::core::get()->add_global_attribute("TimeStamp", boost::make_shared< TimeStamp >());
And used like this:
backend_ptr->set_formatter(
boost::log::formatters::stream
<< boost::log::formatters::attr< std::string >("TimeStamp")
<< boost::log::formatters::message();
The class, obviously, lets us access or format any portion of the date we wish
Try this one. It works for me under Linux.
sink->set_formatter(log_expr::format("%1%") % log_expr::max_size_decor<char>(22)[log_expr::stream << log_expr::format_date_time<boost::posix_time::ptime>("Timestamp", "%Y-%m-%d %H:%M:%S.%f")]);

Resources