<commit_before>#include "framework/trace.h"
#include "framework/configfile.h"
#include <chrono>
#include <fstream>
#include <list>
#include <memory>
#include <mutex>
#include <sstream>
#include <thread>
#include <utility>
#include <vector>

namespace
{

using OpenApoc::UString;

OpenApoc::ConfigOptionBool enableTrace("Trace", "enable", "Enable json call/time tracking");
OpenApoc::ConfigOptionString traceFile("Trace", "outputFile", "File to output trace json to",
                                       "openapoc.trace");

const unsigned int TRACE_CHUNK_SIZE = 100000;

static bool traceInited = false;

static void initTrace()
{
	traceInited = true;
	if (enableTrace.get())
		OpenApoc::Trace::enable();
}

enum class EventType : unsigned char
{
	Begin,
	End,
};

class TraceEvent
{
  public:
	EventType type;
	uint64_t timeNS : 48; // (2^48) nanoseconds = 3.25781223 days
	UString name;
	std::vector<std::pair<UString, UString>> args;<commit_msg>Fix race between multiple threads initing the tracer<commit_after>#include "framework/trace.h"
#include "framework/configfile.h"
#include <chrono>
#include <fstream>
#include <list>
#include <memory>
#include <mutex>
#include <sstream>
#include <thread>
#include <utility>
#include <vector>

namespace
{

using OpenApoc::UString;

OpenApoc::ConfigOptionBool enableTrace("Trace", "enable", "Enable json call/time tracking");
OpenApoc::ConfigOptionString traceFile("Trace", "outputFile", "File to output trace json to",
                                       "openapoc.trace");

const unsigned int TRACE_CHUNK_SIZE = 100000;

std::mutex initTraceLock;
static bool traceInited = false;

static void initTrace()
{
	std::lock_guard<std::mutex> l(initTraceLock);
	// Something might have enabled this in the time between check and lock
	if (traceInited)
		return;
	traceInited = true;
	if (enableTrace.get())
		OpenApoc::Trace::enable();
}

enum class EventType : unsigned char
{
	Begin,
	End,
};

class TraceEvent
{
  public:
	EventType type;
	uint64_t timeNS : 48; // (2^48) nanoseconds = 3.25781223 days
	UString name;
	std::vector<std::pair<UString, UString>> args;
{'fraction_non_alphanumeric': 0.1273071462375769, 'fraction_numerical': 0.02082347373402745, 'mean_word_length': 4.823691460055096, 'pattern_counts': {'":': 0, '<': 26, '<?xml version=': 0, '>': 26, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6496247', 'n_tokens_mistral': 728, 'n_tokens_neox': 690, 'n_words': 191}