473,796 Members | 2,569 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creating a standard log file that is accessible by all other files

20 New Member
Just a basic question, I want to create a standard log file API and want that API to be shared by all my other python files.
For eg. I have file1 which creates a file handle and hands it over to say log.py

Now say I have file2, and it needs to write into the same log file, how do I achieve this and what is the best way of doing it ?
Expand|Select|Wrap|Line Numbers
  1. -------
  2. File1:
  3. --------
  4.  
  5. log_file = file('out.log',"w")
  6. log_obj = log.log(log_file)
  7.  
  8. log_obj.write("Hello world from File 1") 
  9.  
  10. ----------
  11. log.py 
  12. ----------
  13. class log:
  14.       def __init__(self,log):
  15.          self.log = log 
  16.        def write(self,message):
  17.             self.log.write(message)
  18. ----------
  19. File 2: 
  20. ----------
  21.  
  22. from log import * 
  23. log.write("message from file2")
This obviously will not work because I am passing a str object instead of log instance.

Any tips ?
Mar 28 '07 #1
7 1560
indiarocks
20 New Member
Tried implementing the following method and it seems to work. Not sure if it's a good way to do it.

<code>
Expand|Select|Wrap|Line Numbers
  1. file1.py 
  2. # Declare a global list which can be accessible by other files 
  3. log_list = []
  4.  
  5. def func1():
  6.    global log_list 
  7.    log_file = file('abc.out',"w")
  8.    log_list.append(log_file)
  9.  
  10. </code>
  11.  
  12. <code> 
  13. File2.py 
  14. import log 
  15. import file1 
  16.  
  17. file1.func1() 
  18. log.write("Hello World ")
  19. </code> 
  20.  
  21. <code> 
  22. log.py 
  23. from g import log_list 
  24.  
  25. def write(message):
  26.        log_list[0].write(message) 
  27. </code> 
  28.  
So basically what happens is that when you run file2, file1 creates a log file which can be shared by other files. This one worked because log_list is a list which is mutable and that is imported by log.py. I thought that even log file handlers where mutable, but that didn't work for some reason. And putting that log_file handle within a list seemed to solve the issue.
Mar 28 '07 #2
bvdet
2,851 Recognized Expert Moderator Specialist
Tried implementing the following method and it seems to work. Not sure if it's a good way to do it.

<code>

file1.py
# Declare a global list which can be accessible by other files
log_list = []

def func1():
global log_list
log_file = file('abc.out', "w")
log_list.append (log_file)

</code>

<code>
File2.py
import log
import file1

file1.func1()
log.write("Hell o World ")
</code>

<code>
log.py
from g import log_list

def write(message):
log_list[0].write(message)
</code>

So basically what happens is that when you run file2, file1 creates a log file which can be shared by other files. This one worked because log_list is a list which is mutable and that is imported by log.py. I thought that even log file handlers where mutable, but that didn't work for some reason. And putting that log_file handle within a list seemed to solve the issue.
I see you are trying to use code tags. Good, except use square brackets '[ ]' instead of '< >'.

Why not:
Expand|Select|Wrap|Line Numbers
  1. # file1.py
  2.  
  3. log_file_name = r'H:\TEMP\log.txt'
  4.  
  5. ............................................................
  6.  
  7.  
  8. # log_file.py
  9.  
  10. import file1
  11.  
  12. # open log file
  13. f = open(file1.log_file_name, 'a')
  14. .............................................
Mar 28 '07 #3
ghostdog74
511 Recognized Expert Contributor
actually you don't to create your own. Python has a logger module. Unless of course, you have other requirements.
Mar 29 '07 #4
indiarocks
20 New Member
I see you are trying to use code tags. Good, except use square brackets '[ ]' instead of '< >'.

Why not:
Expand|Select|Wrap|Line Numbers
  1. # file1.py
  2.  
  3. log_file_name = r'H:\TEMP\log.txt'
  4.  
  5. ............................................................
  6.  
  7.  
  8. # log_file.py
  9.  
  10. import file1
  11.  
  12. # open log file
  13. f = open(file1.log_file_name, 'a')
  14. .............................................
In this case if I have my program spread across 15 files, I need to explicitly open each of the files in these 15 files. To avoid that I created a general log function which can be imported by other files and they can directly use as log(msg)
Mar 29 '07 #5
bvdet
2,851 Recognized Expert Moderator Specialist
In this case if I have my program spread across 15 files, I need to explicitly open each of the files in these 15 files. To avoid that I created a general log function which can be imported by other files and they can directly use as log(msg)
Gotcha. For some reason I thought you were just needing the file name. Is it working well?
Mar 30 '07 #6
bartonc
6,596 Recognized Expert Expert
In this case if I have my program spread across 15 files, I need to explicitly open each of the files in these 15 files. To avoid that I created a general log function which can be imported by other files and they can directly use as log(msg)
They're called 'tags', so (if you know HTML) in makes sense to use
<code>
</code>
But on this site, we use [code] and the next one has the forward slash (but if I put it here it will disappear. You can use the # button at the top of the editor.
Mar 30 '07 #7
indiarocks
20 New Member
Gotcha. For some reason I thought you were just needing the file name. Is it working well?
Yeah, seems to be working well.

Thanks
Mar 30 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

4
2759
by: Edvard Majakari | last post by:
Greetings, fellow Pythonistas! I'm about to create three modules. As an avid TDD fan I'd like to create typical 'use-cases' for each of these modules. One of them is rather large, and I wondered if it would be easy enough to create a code skeleton out of unit test module. Consider the following, though contrived, unit test code snippet: ==========================================================================
1
1028
by: santhosh_176 | last post by:
:I Created a Pocket PC application for iPAQ 5450. Every thing went fine even installer creation. I could run the setup and install it into the actual device and worked fine. The application enables syncronization with remote database using merge replication. I found contradictory results while installing the application. I will mention here all the steps that I done while creating and installing setups. Result: Case 1: worked fine. ...
15
6751
by: Carlos Lozano | last post by:
Hi, What is the right way to create an OCX COM component. The component is already registerred, but can't create an instance. I am using the reference to the interop module created. If I use javascript or vbscript it works. I will appreciate any help. I do the following (C#):
1
1008
by: Matt Tapia | last post by:
I want to create several files that will be accessible through the asp.net interface. I can call a stored procedure to create the file on the SQL server, however the asp.net user does not have permission to access the file. What is the best way?
2
1213
by: | last post by:
Hi all, I have vs.net 2003 locally installed on my XP PRO machine. I have a web server on the LAN which has a website configured at http://services. This is accessible via my web browser and already has a web service (built using sdk and notepad) at http://services/services/services.asmx. Now I am trying to create a new web service "services2.asmx" in vs.net. I click on File-->New-->Project. Then select Asp.net Web Service under VB...
12
3176
by: Mats Lycken | last post by:
Hi, I'm creating a CMS that I would like to be plug-in based with different plugins handling different kinds of content. What I really want is to be able to load/unload plugins on the fly without restarting the application. What I did was to create an AppDomain that loaded the plugins and everything was great, until I tried to pass something else that strings between the domains...
1
2739
by: Dan | last post by:
I have an application that I want to use for copying files. My goal is to copy a files, if a file is in use or not accessible because of security reasons I want to make note of that file then continue with the file copy process. For some reason when my app is copying the C:\Windows\System32\Config folder it will fail on the first non-accessible file then ends the copy process. It only seems to happen on this folder (folder contains...
270
9583
by: jacob navia | last post by:
In my "Happy Christmas" message, I proposed a function to read a file into a RAM buffer and return that buffer or NULL if the file doesn't exist or some other error is found. It is interesting to see that the answers to that message prove that programming exclusively in standard C is completely impossible even for a small and ridiculously simple program like the one I proposed. 1 I read the file contents in binary mode, what should...
3
2983
by: Ed | last post by:
Hi, dear all, Sometimes, when I debug my program, VS seems very smart to find the cpp file even if the file was not in the working directory. I am wondering how did VS try to find the cpp file when we debug program. Even walking through every menu items, I can not find the related information. What's the rules of it? Or, can we set the search path of it?
0
9680
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9528
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10455
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10173
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10006
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7547
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6788
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5441
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2925
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.