File indexing completed on 2025-07-06 08:34:53
0001 #pragma once
0002
0003 #include <iostream>
0004 #include <vector>
0005 #include <string>
0006 #include <mutex>
0007
0008 #include <JANA/JApplicationFwd.h>
0009 #include "services/log/Log_service.h"
0010 #include <JANA/Services/JGlobalRootLock.h>
0011 #include <JANA/Services/JServiceLocator.h>
0012
0013 #include <TFile.h>
0014
0015
0016
0017
0018 class RootFile_service : public JService {
0019 public:
0020 explicit RootFile_service(JApplication* app) : m_app(app) {}
0021 ~RootFile_service() override { CloseHistFile(); }
0022
0023 void acquire_services(JServiceLocator* ) override {
0024 auto log_service = m_app->GetService<Log_service>();
0025 m_log = log_service->logger("RootFile");
0026 }
0027
0028
0029
0030
0031
0032
0033
0034
0035
0036
0037
0038
0039
0040
0041
0042
0043
0044
0045
0046
0047
0048
0049 TDirectory* GetHistFile(bool create_if_needed = true) {
0050
0051 if (create_if_needed) {
0052 std::call_once(init_flag, &RootFile_service::CreateHistFile, this);
0053 }
0054 return m_histfile;
0055 }
0056
0057
0058
0059
0060
0061
0062
0063
0064
0065
0066
0067 void CloseHistFile() {
0068 if (m_histfile) {
0069 std::string filename = m_histfile->GetName();
0070 m_histfile->Write();
0071 delete m_histfile;
0072 m_log->info("Closed user histogram file: {}", filename);
0073 }
0074 m_histfile = nullptr;
0075 }
0076
0077 private:
0078
0079
0080 void CreateHistFile() {
0081
0082 std::string filename = "eicrecon.root";
0083 m_app->SetDefaultParameter("histsfile", filename,
0084 "Name of root file to be created for plugin histograms/trees");
0085 if (!m_histfile) {
0086 try {
0087 m_histfile = new TFile(filename.c_str(), "RECREATE", "user histograms/trees");
0088 m_log->info("Created file: {} for user histograms", filename);
0089 } catch (std::exception& ex) {
0090 m_log->error("Problem opening root file for histograms: {}", ex.what());
0091 throw ex;
0092 }
0093 }
0094 }
0095
0096 RootFile_service() = default;
0097
0098 JApplication* m_app = nullptr;
0099 std::shared_ptr<spdlog::logger> m_log;
0100 TFile* m_histfile = nullptr;
0101 std::once_flag init_flag;
0102 };