Version 5.4.3.2, tag libreoffice-5.4.3.2
[LibreOffice.git] / extensions / source / logging / filehandler.cxx
bloba59a43cb9800c3220b2fb99ebfd383d5bf0b6301
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <sal/config.h>
22 #include "methodguard.hxx"
23 #include "loghandler.hxx"
25 #include <com/sun/star/logging/XLogHandler.hpp>
26 #include <com/sun/star/lang/XServiceInfo.hpp>
27 #include <com/sun/star/lang/IllegalArgumentException.hpp>
28 #include <com/sun/star/util/PathSubstitution.hpp>
29 #include <com/sun/star/util/XStringSubstitution.hpp>
31 #include <tools/diagnose_ex.h>
33 #include <cppuhelper/compbase.hxx>
34 #include <cppuhelper/basemutex.hxx>
35 #include <cppuhelper/supportsservice.hxx>
37 #include <osl/thread.h>
38 #include <osl/file.hxx>
39 #include <rtl/strbuf.hxx>
41 #include <memory>
43 namespace logging
45 using ::com::sun::star::uno::Reference;
46 using ::com::sun::star::logging::LogRecord;
47 using ::com::sun::star::uno::RuntimeException;
48 using ::com::sun::star::logging::XLogFormatter;
49 using ::com::sun::star::uno::Sequence;
50 using ::com::sun::star::uno::XInterface;
51 using ::com::sun::star::uno::XComponentContext;
52 using ::com::sun::star::logging::XLogHandler;
53 using ::com::sun::star::lang::XServiceInfo;
54 using ::com::sun::star::uno::Exception;
55 using ::com::sun::star::lang::IllegalArgumentException;
56 using ::com::sun::star::util::PathSubstitution;
57 using ::com::sun::star::util::XStringSubstitution;
58 using ::com::sun::star::beans::NamedValue;
60 typedef ::cppu::WeakComponentImplHelper < XLogHandler
61 , XServiceInfo
62 > FileHandler_Base;
63 class FileHandler :public ::cppu::BaseMutex
64 ,public FileHandler_Base
66 private:
67 enum FileValidity
69 /// never attempted to open the file
70 eUnknown,
71 /// file is valid
72 eValid,
73 /// file is invalid
74 eInvalid
77 Reference<XComponentContext> m_xContext;
78 LogHandlerHelper m_aHandlerHelper;
79 OUString m_sFileURL;
80 std::unique_ptr< ::osl::File > m_pFile;
81 FileValidity m_eFileValidity;
83 public:
84 FileHandler(const css::uno::Reference<XComponentContext> &context,
85 const css::uno::Sequence<css::uno::Any> &arguments);
86 virtual ~FileHandler() override;
88 private:
89 // XLogHandler
90 virtual OUString SAL_CALL getEncoding() override;
91 virtual void SAL_CALL setEncoding( const OUString& _encoding ) override;
92 virtual Reference< XLogFormatter > SAL_CALL getFormatter() override;
93 virtual void SAL_CALL setFormatter( const Reference< XLogFormatter >& _formatter ) override;
94 virtual ::sal_Int32 SAL_CALL getLevel() override;
95 virtual void SAL_CALL setLevel( ::sal_Int32 _level ) override;
96 virtual void SAL_CALL flush( ) override;
97 virtual sal_Bool SAL_CALL publish( const LogRecord& Record ) override;
99 // XServiceInfo
100 virtual OUString SAL_CALL getImplementationName() override;
101 virtual sal_Bool SAL_CALL supportsService( const OUString& _rServiceName ) override;
102 virtual Sequence< OUString > SAL_CALL getSupportedServiceNames() override;
104 // OComponentHelper
105 virtual void SAL_CALL disposing() override;
107 public:
108 typedef ComponentMethodGuard< FileHandler > MethodGuard;
109 void enterMethod( MethodGuard::Access );
110 void leaveMethod( MethodGuard::Access );
112 private:
113 /** prepares our output file for writing
115 bool impl_prepareFile_nothrow();
117 /// writes the given string to our file
118 void impl_writeString_nothrow( const OString& _rEntry );
120 /** does string substitution on a (usually externally provided) file url
122 void impl_doStringsubstitution_nothrow( OUString& _inout_rURL );
125 FileHandler::FileHandler(const css::uno::Reference<XComponentContext> &context,
126 const css::uno::Sequence<css::uno::Any> &arguments)
127 :FileHandler_Base( m_aMutex )
128 ,m_xContext( context )
129 ,m_aHandlerHelper( context, m_aMutex, rBHelper )
130 ,m_sFileURL( )
131 ,m_pFile( )
132 ,m_eFileValidity( eUnknown )
134 ::osl::MutexGuard aGuard( m_aMutex );
136 if ( arguments.getLength() != 1 )
137 throw IllegalArgumentException( OUString(), *this, 1 );
139 Sequence< NamedValue > aSettings;
140 if ( arguments[0] >>= m_sFileURL )
142 // create( [in] string URL );
143 impl_doStringsubstitution_nothrow( m_sFileURL );
145 else if ( arguments[0] >>= aSettings )
147 // createWithSettings( [in] sequence< css::beans::NamedValue > Settings )
148 ::comphelper::NamedValueCollection aTypedSettings( aSettings );
149 m_aHandlerHelper.initFromSettings( aTypedSettings );
151 if ( aTypedSettings.get_ensureType( "FileURL", m_sFileURL ) )
152 impl_doStringsubstitution_nothrow( m_sFileURL );
154 else
155 throw IllegalArgumentException( OUString(), *this, 1 );
157 m_aHandlerHelper.setIsInitialized();
160 FileHandler::~FileHandler()
162 if ( !rBHelper.bDisposed )
164 acquire();
165 dispose();
170 bool FileHandler::impl_prepareFile_nothrow()
172 if ( m_eFileValidity == eUnknown )
174 m_pFile.reset( new ::osl::File( m_sFileURL ) );
175 // check whether the log file already exists
176 ::osl::DirectoryItem aFileItem;
177 ::osl::DirectoryItem::get( m_sFileURL, aFileItem );
178 ::osl::FileStatus aStatus( osl_FileStatus_Mask_Validate );
179 if ( ::osl::FileBase::E_None == aFileItem.getFileStatus( aStatus ) )
180 ::osl::File::remove( m_sFileURL );
182 ::osl::FileBase::RC res = m_pFile->open( osl_File_OpenFlag_Write | osl_File_OpenFlag_Create );
183 m_eFileValidity = res == ::osl::FileBase::E_None
184 ? eValid
185 : eInvalid;
186 #if OSL_DEBUG_LEVEL > 0
187 if ( m_eFileValidity == eInvalid )
189 OStringBuffer sMessage;
190 sMessage.append( "FileHandler::impl_prepareFile_nothrow: could not open the designated log file:" );
191 sMessage.append( "\nURL: " );
192 sMessage.append( OString( m_sFileURL.getStr(), m_sFileURL.getLength(), osl_getThreadTextEncoding() ) );
193 sMessage.append( "\nerror code: " );
194 sMessage.append( (sal_Int32)res );
195 OSL_FAIL( sMessage.makeStringAndClear().getStr() );
197 #endif
198 if ( m_eFileValidity == eValid )
200 OString sHead;
201 if ( m_aHandlerHelper.getEncodedHead( sHead ) )
202 impl_writeString_nothrow( sHead );
206 return m_eFileValidity == eValid;
210 void FileHandler::impl_writeString_nothrow( const OString& _rEntry )
212 OSL_PRECOND( m_pFile.get(), "FileHandler::impl_writeString_nothrow: no file!" );
214 sal_uInt64 nBytesToWrite( _rEntry.getLength() );
215 sal_uInt64 nBytesWritten( 0 );
216 ::osl::FileBase::RC res =
217 m_pFile->write( _rEntry.getStr(), nBytesToWrite, nBytesWritten );
218 OSL_ENSURE( ( res == ::osl::FileBase::E_None ) && ( nBytesWritten == nBytesToWrite ),
219 "FileHandler::impl_writeString_nothrow: could not write the log entry!" );
223 void FileHandler::impl_doStringsubstitution_nothrow( OUString& _inout_rURL )
227 Reference< XStringSubstitution > xStringSubst(PathSubstitution::create(m_xContext));
228 _inout_rURL = xStringSubst->substituteVariables( _inout_rURL, true );
230 catch( const Exception& )
232 DBG_UNHANDLED_EXCEPTION();
237 void SAL_CALL FileHandler::disposing()
239 if ( m_eFileValidity == eValid )
241 OString sTail;
242 if ( m_aHandlerHelper.getEncodedTail( sTail ) )
243 impl_writeString_nothrow( sTail );
246 m_pFile.reset();
247 m_aHandlerHelper.setFormatter( nullptr );
251 void FileHandler::enterMethod( MethodGuard::Access )
253 m_aHandlerHelper.enterMethod();
257 void FileHandler::leaveMethod( MethodGuard::Access )
259 m_aMutex.release();
263 OUString SAL_CALL FileHandler::getEncoding()
265 MethodGuard aGuard( *this );
266 OUString sEncoding;
267 OSL_VERIFY( m_aHandlerHelper.getEncoding( sEncoding ) );
268 return sEncoding;
272 void SAL_CALL FileHandler::setEncoding( const OUString& _rEncoding )
274 MethodGuard aGuard( *this );
275 OSL_VERIFY( m_aHandlerHelper.setEncoding( _rEncoding ) );
279 Reference< XLogFormatter > SAL_CALL FileHandler::getFormatter()
281 MethodGuard aGuard( *this );
282 return m_aHandlerHelper.getFormatter();
286 void SAL_CALL FileHandler::setFormatter( const Reference< XLogFormatter >& _rxFormatter )
288 MethodGuard aGuard( *this );
289 m_aHandlerHelper.setFormatter( _rxFormatter );
293 ::sal_Int32 SAL_CALL FileHandler::getLevel()
295 MethodGuard aGuard( *this );
296 return m_aHandlerHelper.getLevel();
300 void SAL_CALL FileHandler::setLevel( ::sal_Int32 _nLevel )
302 MethodGuard aGuard( *this );
303 m_aHandlerHelper.setLevel( _nLevel );
307 void SAL_CALL FileHandler::flush( )
309 MethodGuard aGuard( *this );
310 if(!m_pFile.get())
312 OSL_PRECOND(false, "FileHandler::flush: no file!");
313 return;
315 ::osl::FileBase::RC res = m_pFile->sync();
316 OSL_ENSURE(res == ::osl::FileBase::E_None, "FileHandler::flush: Could not sync logfile to filesystem.");
320 sal_Bool SAL_CALL FileHandler::publish( const LogRecord& _rRecord )
322 MethodGuard aGuard( *this );
324 if ( !impl_prepareFile_nothrow() )
325 return false;
327 OString sEntry;
328 if ( !m_aHandlerHelper.formatForPublishing( _rRecord, sEntry ) )
329 return false;
331 impl_writeString_nothrow( sEntry );
332 return true;
335 OUString SAL_CALL FileHandler::getImplementationName()
337 return OUString("com.sun.star.comp.extensions.FileHandler");
340 sal_Bool SAL_CALL FileHandler::supportsService( const OUString& _rServiceName )
342 return cppu::supportsService(this, _rServiceName);
345 Sequence< OUString > SAL_CALL FileHandler::getSupportedServiceNames()
347 return { "com.sun.star.logging.FileHandler" };
350 } // namespace logging
352 extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * SAL_CALL
353 com_sun_star_comp_extensions_FileHandler(
354 css::uno::XComponentContext *context,
355 css::uno::Sequence<css::uno::Any> const &arguments)
357 return cppu::acquire(new logging::FileHandler(context, arguments));
360 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */