One line log: quote addinfo, log record syntax
[metaproxy-moved-to-github.git] / src / filter_log.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 2005-2012 Index Data
3
4 Metaproxy is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17 */
18
19 #include "config.hpp"
20 #include "filter_log.hpp"
21 #include <metaproxy/package.hpp>
22
23 #include <string>
24 #include <sstream>
25 #include <iomanip>
26 #include <boost/thread/mutex.hpp>
27
28 #include "gduutil.hpp"
29 #include <metaproxy/util.hpp>
30 #include <metaproxy/xmlutil.hpp>
31
32 #include <yaz/oid_db.h>
33 #include <yaz/zgdu.h>
34 #include <yaz/wrbuf.h>
35 #include <yaz/log.h>
36 #include <yaz/querytowrbuf.h>
37 #include <yaz/timing.h>
38 #include <stdio.h>
39 #include <time.h>
40
41 namespace mp = metaproxy_1;
42 namespace yf = metaproxy_1::filter;
43
44 namespace metaproxy_1 {
45     namespace filter {
46         class Log::Impl {
47         public:
48             class LFile;
49             typedef boost::shared_ptr<Log::Impl::LFile> LFilePtr;
50         public:
51             //Impl();
52             Impl(const std::string &x = "-");
53            ~Impl();
54             void process(metaproxy_1::Package & package);
55             void configure(const xmlNode * ptr);
56         private:
57             void openfile(const std::string &fname);
58             // needs to be static to be called by C pointer-to-function-syntax
59             static void stream_write(ODR o, void *handle, int type, 
60                               const char *buf, int len);
61             // needs to be static to be called by C pointer-to-function-syntax
62             static void option_write(const char *name, void *handle);
63         private:
64             std::string m_msg_config;
65             bool m_1line;
66             bool m_access;
67             bool m_user_access;
68             bool m_req_apdu;
69             bool m_res_apdu;
70             bool m_req_session;
71             bool m_res_session;
72             bool m_init_options;
73             LFilePtr m_file;
74             std::string m_time_format;
75             // Only used during confiqgure stage (no threading), 
76             // for performance avoid opening files which other log filter 
77             // instances already have opened
78             static std::list<LFilePtr> filter_log_files;
79
80             boost::mutex m_session_mutex;
81             std::map<mp::Session, std::string> m_sessions;
82        };
83
84         class Log::Impl::LFile {
85         public:
86             boost::mutex m_mutex;
87             std::string m_fname;
88             FILE *fhandle;
89             ~LFile();
90             LFile(std::string fname);
91             LFile(std::string fname, FILE *outf);
92             void log(const std::string &date_format,
93                      std::ostringstream &os);
94             void flush();
95         };
96         
97     }
98 }
99
100 // define Pimpl wrapper forwarding to Impl
101  
102 yf::Log::Log() : m_p(new Impl)
103 {
104 }
105
106 yf::Log::Log(const std::string &x) : m_p(new Impl(x))
107 {
108 }
109
110 yf::Log::~Log()
111 {  // must have a destructor because of boost::scoped_ptr
112 }
113
114 void yf::Log::configure(const xmlNode *xmlnode, bool test_only,
115                         const char *path)
116 {
117     m_p->configure(xmlnode);
118 }
119
120 void yf::Log::process(mp::Package &package) const
121 {
122     m_p->process(package);
123 }
124
125
126 // static initialization
127 std::list<yf::Log::Impl::LFilePtr> yf::Log::Impl::filter_log_files;
128
129
130 yf::Log::Impl::Impl(const std::string &x)
131     : m_msg_config(x),
132       m_1line(false),
133       m_access(true),
134       m_user_access(false),
135       m_req_apdu(false),
136       m_res_apdu(false),
137       m_req_session(false),
138       m_res_session(false),
139       m_init_options(false),
140       m_time_format("%H:%M:%S-%d/%m")
141 {
142     openfile("");
143 }
144
145
146 yf::Log::Impl::~Impl() 
147 {
148 }
149
150 static void log_DefaultDiagFormat(WRBUF w, Z_DefaultDiagFormat *e)
151 {
152     if (e->condition)
153         wrbuf_printf(w, ODR_INT_PRINTF " ", *e->condition);
154     else
155         wrbuf_puts(w, "?? ");
156     if (e->which == Z_DefaultDiagFormat_v2Addinfo && e->u.v2Addinfo)
157     {
158         wrbuf_puts(w, "\"");
159         wrbuf_puts(w, e->u.v2Addinfo);
160         wrbuf_puts(w, "\"");
161     }
162     else if (e->which == Z_DefaultDiagFormat_v3Addinfo && e->u.v3Addinfo)
163     {
164         wrbuf_puts(w, "\"");
165         wrbuf_puts(w, e->u.v3Addinfo);
166         wrbuf_puts(w, "\"");
167     }
168     else
169         wrbuf_puts(w, "-");
170 }
171
172 static void log_DiagRecs(WRBUF w, int num_diagRecs, Z_DiagRec **diags)
173 {
174     if (diags[0]->which != Z_DiagRec_defaultFormat)
175         wrbuf_puts(w ,"(diag not in default format?)");
176     else
177     {
178         Z_DefaultDiagFormat *e = diags[0]->u.defaultFormat;
179         log_DefaultDiagFormat(w, e);
180     }
181 }
182
183 static void log_syntax(WRBUF w, const Odr_oid *syntax)
184 {
185     if (syntax)
186     {
187         char oid_name[OID_STR_MAX+1];
188         wrbuf_puts(w, yaz_oid_to_string_buf(syntax, 0, oid_name));
189     }
190     else
191         wrbuf_puts(w, "-");
192 }
193
194 static void log_1_line(Z_APDU *z_req, Z_APDU *z_res, WRBUF w)
195 {
196     switch (z_req->which)
197     {
198     case Z_APDU_initRequest:
199         wrbuf_puts(w, "Init ");
200         if (z_res->which != Z_APDU_initResponse)
201             wrbuf_printf(w, "? response=%d", z_res->which);
202         else
203         {
204             Z_InitRequest *req = z_req->u.initRequest;
205             Z_InitResponse *res = z_res->u.initResponse;
206             if (res->result && *res->result)
207                 wrbuf_printf(w, "OK -");
208             else
209             {
210                 Z_External *uif = res->userInformationField;
211                 bool got_code = false;
212                 wrbuf_printf(w, "ERROR ");
213                 if (uif && uif->which == Z_External_userInfo1)
214                 {
215                     Z_OtherInformation *ui = uif->u.userInfo1;
216                     if (ui->num_elements >= 1)
217                     {
218                         Z_OtherInformationUnit *unit = ui->list[0];
219                         if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
220                             unit->information.externallyDefinedInfo &&
221                             unit->information.externallyDefinedInfo->which ==
222                             Z_External_diag1)
223                         {
224                             Z_DiagnosticFormat *diag =
225                                 unit->information.externallyDefinedInfo->
226                                 u.diag1;
227                             if (diag->num >= 1)
228                             {
229                                 Z_DiagnosticFormat_s *ds = diag->elements[0];
230                                 if (ds->which ==
231                                     Z_DiagnosticFormat_s_defaultDiagRec)
232                                 {
233                                     log_DefaultDiagFormat(w,
234                                                           ds->u.defaultDiagRec);
235                                     got_code = true;
236                                 }
237                             }
238
239                         }
240                     }
241                 }
242                 if (!got_code)
243                     wrbuf_puts(w, "-");
244             }
245             wrbuf_printf(w, " ID:%s Name:%s Version:%s",
246                          req->implementationId ? req->implementationId :"-", 
247                          req->implementationName ?req->implementationName : "-",
248                          req->implementationVersion ?
249                          req->implementationVersion : "-");
250         }
251         break;
252     case Z_APDU_searchRequest:
253         wrbuf_puts(w, "Search ");
254         if (z_res->which != Z_APDU_searchResponse)
255             wrbuf_printf(w, "? response=%d", z_res->which);
256         else
257         {
258             Z_SearchRequest *req = z_req->u.searchRequest;
259             Z_SearchResponse *res = z_res->u.searchResponse;
260             int i;
261             for (i = 0 ; i < req->num_databaseNames; i++)
262             {
263                 if (i)
264                     wrbuf_printf(w, "+");
265                 wrbuf_puts(w, req->databaseNames[i]);
266             }
267             wrbuf_printf(w, " ");
268             if (!res->records)
269             {
270                 wrbuf_printf(w, "OK " ODR_INT_PRINTF " %s", *res->resultCount,
271                              req->resultSetName);
272             }
273             else if (res->records->which == Z_Records_DBOSD)
274             {
275                 wrbuf_printf(w, "OK " ODR_INT_PRINTF " %s", *res->resultCount,
276                              req->resultSetName);
277             }
278             else if (res->records->which == Z_Records_NSD)
279             {
280                 wrbuf_puts(w, "ERROR ");
281                 log_DefaultDiagFormat(w,
282                                       res->records->u.nonSurrogateDiagnostic);
283             }
284             else if (res->records->which == Z_Records_multipleNSD)
285             {
286                 wrbuf_puts(w, "ERROR ");
287                 log_DiagRecs(
288                     w, 
289                     res->records->u.multipleNonSurDiagnostics->num_diagRecs,
290                     res->records->u.multipleNonSurDiagnostics->diagRecs);
291             }
292             wrbuf_puts(w, " ");
293             log_syntax(w, req->preferredRecordSyntax);
294             wrbuf_printf(w, " 1+" ODR_INT_PRINTF " ",
295                          res->numberOfRecordsReturned
296                          ? *res->numberOfRecordsReturned : 0);
297             yaz_query_to_wrbuf(w, req->query);
298         }
299         break;
300     case Z_APDU_presentRequest:
301         wrbuf_puts(w, "Present ");
302         if (z_res->which != Z_APDU_presentResponse)
303             wrbuf_printf(w, "? response=%d", z_res->which);
304         else
305         {
306             Z_PresentRequest *req = z_req->u.presentRequest;
307             Z_PresentResponse *res = z_res->u.presentResponse;
308
309             if (!res->records)
310             {
311                 wrbuf_printf(w, "OK");
312             }
313             else if (res->records->which == Z_Records_DBOSD)
314             {
315                 wrbuf_printf(w, "OK");
316             }
317             else if (res->records->which == Z_Records_NSD)
318             {
319                 wrbuf_puts(w, "ERROR ");
320                 log_DefaultDiagFormat(w,
321                                       res->records->u.nonSurrogateDiagnostic);
322             }
323             else if (res->records->which == Z_Records_multipleNSD)
324             {
325                 wrbuf_puts(w, "ERROR ");
326                 log_DiagRecs(
327                     w, 
328                     res->records->u.multipleNonSurDiagnostics->num_diagRecs,
329                     res->records->u.multipleNonSurDiagnostics->diagRecs);
330             }
331             wrbuf_puts(w, " ");
332             assert(req->preferredRecordSyntax);
333             log_syntax(w, req->preferredRecordSyntax);
334                        
335             wrbuf_printf(w, " %s " ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
336                 req->resultSetId, *req->resultSetStartPoint,
337                          *req->numberOfRecordsRequested);
338         }
339         break;
340     case Z_APDU_deleteResultSetRequest:
341         wrbuf_puts(w, "deleteResultSet ");
342         break;
343     case Z_APDU_accessControlRequest:
344         wrbuf_puts(w, "accessControl ");
345         break;
346     case Z_APDU_resourceControlRequest:
347         wrbuf_puts(w, "resourceControl ");
348         break;
349     case Z_APDU_triggerResourceControlRequest:
350         wrbuf_puts(w, "triggerResourceControlRequest");
351         break;
352     case Z_APDU_resourceReportRequest:
353         wrbuf_puts(w, "resourceReport ");
354         break;
355     case Z_APDU_scanRequest:
356         wrbuf_puts(w, "Scan ");
357         if (z_res->which != Z_APDU_scanResponse)
358             wrbuf_printf(w, "? response=%d", z_res->which);
359         else
360         {
361             Z_ScanRequest *req = z_req->u.scanRequest;
362             Z_ScanResponse *res = z_res->u.scanResponse;
363             int i;
364             for (i = 0 ; i < req->num_databaseNames; i++)
365             {
366                 if (i)
367                     wrbuf_printf(w, "+");
368                 wrbuf_puts(w, req->databaseNames[i]);
369             }
370             wrbuf_puts(w, " ");
371             if (!res->scanStatus || *res->scanStatus == 0)
372                 wrbuf_puts(w, "OK");
373             else if (*res->scanStatus == 6)
374                 wrbuf_puts(w, "ERROR");
375             else
376                 wrbuf_printf(w, "PARTIAL" ODR_INT_PRINTF, *res->scanStatus);
377             
378             wrbuf_printf(w, " " ODR_INT_PRINTF " " ODR_INT_PRINTF "+" 
379                          ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
380                          res->numberOfEntriesReturned ?
381                          *res->numberOfEntriesReturned : 0,
382                          req->preferredPositionInResponse ?
383                           *req->preferredPositionInResponse : 1,
384                          *req->numberOfTermsRequested,
385                          res->stepSize ? *res->stepSize : 1);
386             
387             yaz_scan_to_wrbuf(w, req->termListAndStartPoint, 
388                               req->attributeSet);
389         }
390         break;
391     case Z_APDU_sortRequest:
392         wrbuf_puts(w, "sort ");
393         if (z_res->which != Z_APDU_sortResponse)
394             wrbuf_printf(w, "? response=%d", z_res->which);
395         else
396         {
397             Z_SortResponse *res = z_res->u.sortResponse;
398             Z_SortRequest *req = z_res->u.sortRequest;
399             int i;
400
401             if (*res->sortStatus == Z_SortResponse_success)
402                 wrbuf_puts(w, "OK");
403             else if (*res->sortStatus == Z_SortResponse_partial_1) 
404                 wrbuf_puts(w, "PARTIAL");
405             else if (*res->sortStatus == Z_SortResponse_failure)
406                 wrbuf_puts(w, "ERROR");
407
408             wrbuf_puts(w, " ");
409             if (res->diagnostics && res->num_diagnostics >= 1)
410                 log_DiagRecs(w, res->num_diagnostics,res->diagnostics);
411             else
412                 wrbuf_puts(w, "-");
413
414             wrbuf_puts(w, " (");
415             for (i = 0; i < req->num_inputResultSetNames; i++)
416             {
417                 if (i)
418                     wrbuf_puts(w, "+");
419                 wrbuf_puts(w, req->inputResultSetNames[i]);
420             }
421             wrbuf_printf(w, ")->%s ",req->sortedResultSetName);
422
423         }
424         break;
425     case Z_APDU_segmentRequest:
426         wrbuf_puts(w, "segmentRequest");
427         break;
428     case Z_APDU_extendedServicesRequest:
429         wrbuf_puts(w, "extendedServices");
430         if (z_res->which != Z_APDU_extendedServicesResponse)
431             wrbuf_printf(w, "? response=%d", z_res->which);
432         else
433         {
434             Z_ExtendedServicesResponse *res =
435                 z_res->u.extendedServicesResponse;
436             switch (*res->operationStatus)
437             {
438             case Z_ExtendedServicesResponse_done:
439                 wrbuf_puts(w, "DONE"); break;
440             case Z_ExtendedServicesResponse_accepted:
441                 wrbuf_puts(w, "ACCEPTED"); break;
442             case Z_ExtendedServicesResponse_failure:
443                 wrbuf_puts(w, "ERROR"); break;
444             default:
445                 wrbuf_printf(w, ODR_INT_PRINTF, *res->operationStatus);
446             }
447             wrbuf_puts(w, " ");
448             if (res->diagnostics && res->num_diagnostics >= 1)
449                 log_DiagRecs(w, res->num_diagnostics,res->diagnostics);
450             else
451                 wrbuf_puts(w, "-");      
452         }
453         break;
454     case Z_APDU_close:
455         wrbuf_puts(w, "close");
456         break;
457     case Z_APDU_duplicateDetectionRequest:
458         wrbuf_puts(w, "duplicateDetention ");
459         if (z_res->which != Z_APDU_duplicateDetectionResponse)
460             wrbuf_printf(w, "? response=%d", z_res->which);
461         else
462         {
463             Z_DuplicateDetectionResponse *res =
464                 z_res->u.duplicateDetectionResponse;
465             if (*res->status)
466                 wrbuf_puts(w, "OK");
467             else
468                 wrbuf_puts(w, "ERROR");
469
470             wrbuf_puts(w, " ");
471             if (res->diagnostics && res->num_diagnostics >= 1)
472                 log_DiagRecs(w, res->num_diagnostics, res->diagnostics);
473             else
474                 wrbuf_puts(w, "-");
475         }
476         break;
477     default:
478         wrbuf_printf(w, "REQ=%d RES=%d", z_req->which, z_res->which);
479     }
480 }
481
482 void yf::Log::Impl::configure(const xmlNode *ptr)
483 {
484     for (ptr = ptr->children; ptr; ptr = ptr->next)
485     {
486         if (ptr->type != XML_ELEMENT_NODE)
487             continue;
488         if (!strcmp((const char *) ptr->name, "message"))
489             m_msg_config = mp::xml::get_text(ptr);
490         else if (!strcmp((const char *) ptr->name, "filename"))
491         {
492             std::string fname = mp::xml::get_text(ptr);
493             openfile(fname);
494         }
495         else if (!strcmp((const char *) ptr->name, "time-format"))
496         {
497             m_time_format = mp::xml::get_text(ptr);
498         }
499         else if (!strcmp((const char *) ptr->name, "category"))
500         {
501             const struct _xmlAttr *attr;
502             for (attr = ptr->properties; attr; attr = attr->next)
503             {
504                 if (!strcmp((const char *) attr->name,  "line"))
505                     m_1line = mp::xml::get_bool(attr->children, true);
506                 else if (!strcmp((const char *) attr->name,  "access"))
507                     m_access = mp::xml::get_bool(attr->children, true);
508                 else if (!strcmp((const char *) attr->name, "user-access"))
509                     m_user_access = mp::xml::get_bool(attr->children, true);
510                 else if (!strcmp((const char *) attr->name, "request-apdu"))
511                     m_req_apdu = mp::xml::get_bool(attr->children, true);
512                 else if (!strcmp((const char *) attr->name, "response-apdu"))
513                     m_res_apdu = mp::xml::get_bool(attr->children, true);
514                 else if (!strcmp((const char *) attr->name, "apdu"))
515                 {
516                     m_req_apdu = mp::xml::get_bool(attr->children, true);
517                     m_res_apdu = m_req_apdu;
518                 }
519                 else if (!strcmp((const char *) attr->name,
520                                  "request-session"))
521                     m_req_session = 
522                         mp::xml::get_bool(attr->children, true);
523                 else if (!strcmp((const char *) attr->name, 
524                                  "response-session"))
525                     m_res_session = 
526                         mp::xml::get_bool(attr->children, true);
527                 else if (!strcmp((const char *) attr->name,
528                                  "session"))
529                 {
530                     m_req_session = 
531                         mp::xml::get_bool(attr->children, true);
532                     m_res_session = m_req_session;
533                 }
534                 else if (!strcmp((const char *) attr->name, 
535                                  "init-options"))
536                     m_init_options = 
537                         mp::xml::get_bool(attr->children, true);
538                 else if (!strcmp((const char *) attr->name, 
539                                  "init-options"))
540                     m_init_options = 
541                         mp::xml::get_bool(attr->children, true);
542                 else
543                     throw mp::filter::FilterException(
544                         "Bad attribute " + std::string((const char *)
545                                                        attr->name));
546             }
547         }
548         else
549         {
550             throw mp::filter::FilterException("Bad element " 
551                                                + std::string((const char *)
552                                                              ptr->name));
553         }
554     }
555 }
556
557 void yf::Log::Impl::process(mp::Package &package)
558 {
559     Z_GDU *gdu_req = package.request().get();
560     std::string user("-");
561
562     yaz_timing_t timer = yaz_timing_create();
563
564     // scope for session lock
565     {
566         boost::mutex::scoped_lock scoped_lock(m_session_mutex);
567         
568         if (gdu_req && gdu_req->which == Z_GDU_Z3950)
569         {
570             Z_APDU *apdu_req = gdu_req->u.z3950;
571             if (apdu_req->which == Z_APDU_initRequest)
572             {
573                 Z_InitRequest *req = apdu_req->u.initRequest;
574                 Z_IdAuthentication *a = req->idAuthentication;
575                 if (a)
576                 {
577                     if (a->which == Z_IdAuthentication_idPass)
578                         user = a->u.idPass->userId;
579                     else if (a->which == Z_IdAuthentication_open)
580                         user = a->u.open;
581                 
582                     m_sessions[package.session()] = user;
583                 }
584             }
585         }
586         std::map<mp::Session,std::string>::iterator it = 
587             m_sessions.find(package.session());
588         if (it != m_sessions.end())
589             user = it->second;
590         
591         if (package.session().is_closed())
592             m_sessions.erase(package.session());
593     }
594     // scope for locking Ostream
595     { 
596         boost::mutex::scoped_lock scoped_lock(m_file->m_mutex);
597  
598         if (m_access)
599         {
600             if (gdu_req)          
601             {
602                 std::ostringstream os;
603                 os  << m_msg_config << " "
604                     << package << " "
605                     << "0.000000" << " " 
606                     << *gdu_req;
607                 m_file->log(m_time_format, os);
608             }
609         }
610
611         if (m_user_access)
612         {
613             if (gdu_req)          
614             {
615                 std::ostringstream os;
616                 os  << m_msg_config << " " << user << " "
617                     << package << " "
618                     << "0.000000" << " " 
619                     << *gdu_req;
620                 m_file->log(m_time_format, os);
621             }
622         }
623
624         if (m_req_session)
625         {
626             std::ostringstream os;
627             os << m_msg_config;
628             os << " request id=" << package.session().id();
629             os << " close=" 
630                << (package.session().is_closed() ? "yes" : "no");
631             m_file->log(m_time_format, os);
632         }
633
634         if (m_init_options)
635         {
636             if (gdu_req && gdu_req->which == Z_GDU_Z3950 &&
637                 gdu_req->u.z3950->which == Z_APDU_initRequest)
638             {
639                 std::ostringstream os;
640                 os << m_msg_config << " init options:";
641                 yaz_init_opt_decode(gdu_req->u.z3950->u.initRequest->options,
642                                     option_write, &os);
643                 m_file->log(m_time_format, os);
644             }
645         }
646         
647         if (m_req_apdu)
648         {
649             if (gdu_req)
650             {
651                 mp::odr odr(ODR_PRINT);
652                 odr_set_stream(odr, m_file->fhandle, stream_write, 0);
653                 z_GDU(odr, &gdu_req, 0, 0);
654             }
655         }
656     }
657     
658     // unlocked during move
659     package.move();
660
661     Z_GDU *gdu_res = package.response().get();
662
663     yaz_timing_stop(timer);
664     double duration = yaz_timing_get_real(timer);
665
666     // scope for locking Ostream 
667     { 
668         boost::mutex::scoped_lock scoped_lock(m_file->m_mutex);
669         
670         if (m_1line)
671         {
672             if (gdu_req && gdu_res && gdu_req->which == Z_GDU_Z3950
673                 && gdu_res->which == Z_GDU_Z3950)
674             {
675                 mp::wrbuf w;
676
677                 log_1_line(gdu_req->u.z3950, gdu_res->u.z3950, w);
678                 const char *message = wrbuf_cstr(w);
679
680                 std::ostringstream os;
681                 os  << m_msg_config << " "
682                     << package << " "
683                     << std::fixed << std::setprecision (6) << duration
684                     << " "
685                     << message;
686                 m_file->log(m_time_format, os);
687             }
688         }
689
690         if (m_access)
691         {
692             if (gdu_res)
693             {
694                 std::ostringstream os;
695                 os  << m_msg_config << " "
696                     << package << " "
697                     << std::fixed << std::setprecision (6) << duration
698                     << " "
699                     << *gdu_res;
700                 m_file->log(m_time_format, os);
701             }
702         }
703         if (m_user_access)
704         {
705             if (gdu_res)
706             {
707                 std::ostringstream os;
708                 os  << m_msg_config << " " << user << " "
709                     << package << " "
710                     << std::fixed << std::setprecision (6) << duration << " "
711                     << *gdu_res;
712                 m_file->log(m_time_format, os);
713             }   
714         }
715
716         if (m_res_session)
717         {
718             std::ostringstream os;
719             os << m_msg_config;
720             os << " response id=" << package.session().id();
721             os << " close=" 
722                << (package.session().is_closed() ? "yes " : "no ")
723                << "duration=" 
724                << std::fixed << std::setprecision (6) << duration;
725             m_file->log(m_time_format, os);
726         }
727
728         if (m_init_options)
729         {
730             if (gdu_res && gdu_res->which == Z_GDU_Z3950 &&
731                 gdu_res->u.z3950->which == Z_APDU_initResponse)
732             {
733                 std::ostringstream os;
734                 os << m_msg_config;
735                 os << " init options:";
736                 yaz_init_opt_decode(gdu_res->u.z3950->u.initResponse->options,
737                                     option_write, &os);
738                 m_file->log(m_time_format, os);
739             }
740         }
741         
742         if (m_res_apdu)
743         {
744             if (gdu_res)
745             {
746                 mp::odr odr(ODR_PRINT);
747                 odr_set_stream(odr, m_file->fhandle, stream_write, 0);
748                 z_GDU(odr, &gdu_res, 0, 0);
749             }
750         }
751     }
752     m_file->flush();
753     yaz_timing_destroy(&timer);
754 }
755
756
757 void yf::Log::Impl::openfile(const std::string &fname)
758 {
759     std::list<LFilePtr>::const_iterator it
760         = filter_log_files.begin();
761     for (; it != filter_log_files.end(); it++)
762     {
763         if ((*it)->m_fname == fname)
764         {
765             m_file = *it;
766             return;
767         }
768     }
769     LFilePtr newfile(new LFile(fname));
770     filter_log_files.push_back(newfile);
771     m_file = newfile;
772 }
773
774
775 void yf::Log::Impl::stream_write(ODR o, void *handle, int type, const char *buf, int len)
776 {
777     FILE *f = (FILE*) handle;
778     fwrite(buf, len, 1, f ? f : yaz_log_file());
779 }
780
781 void yf::Log::Impl::option_write(const char *name, void *handle)
782 {
783     std::ostringstream *os = (std::ostringstream *) handle;
784     *os << " " << name;
785 }
786
787
788 yf::Log::Impl::LFile::LFile(std::string fname) : 
789     m_fname(fname)
790     
791 {
792     if (fname.c_str())
793         fhandle = fopen(fname.c_str(), "a");
794     else
795         fhandle = 0;
796 }
797
798 yf::Log::Impl::LFile::~LFile()
799 {
800 }
801
802 void yf::Log::Impl::LFile::log(const std::string &date_format,
803                                std::ostringstream &os)
804 {
805     if (fhandle)
806     {
807         char datestr[80];
808         time_t ti = time(0);
809 #if HAVE_LOCALTIME_R
810         struct tm tm0, *tm = &tm0;
811         localtime_r(&ti, tm);
812 #else
813         struct tm *tm = localtime(&ti);
814 #endif
815         if (strftime(datestr, sizeof(datestr)-1, date_format.c_str(), tm))
816         {
817             fputs(datestr, fhandle);
818             fputs(" ", fhandle);
819         }
820         fputs(os.str().c_str(), fhandle);
821         fputc('\n', fhandle);
822     }    
823     else
824         yaz_log(YLOG_LOG, "%s", os.str().c_str());
825 }
826
827 void yf::Log::Impl::LFile::flush()
828 {
829     if (fhandle)
830         fflush(fhandle);
831 }
832
833 static mp::filter::Base* filter_creator()
834 {
835     return new mp::filter::Log;
836 }
837
838 extern "C" {
839     struct metaproxy_1_filter_struct metaproxy_1_filter_log = {
840         0,
841         "log",
842         filter_creator
843     };
844 }
845
846 /*
847  * Local variables:
848  * c-basic-offset: 4
849  * c-file-style: "Stroustrup"
850  * indent-tabs-mode: nil
851  * End:
852  * vim: shiftwidth=4 tabstop=8 expandtab
853  */
854