log4php - Change log file Name dynamically in log4php.properties - log4php

hi how can i change the log file name and path in log4php.properties dynamically
log4php.appender.A8.File=../logs/logs.log
Thanks

2 useful pieces of information:
(1) The previous answer by user367134 is helpful, however it has a bug: when setting the level you should not set it to the constant integer value denoted by LoggerLevel::DEBUG. You should instead make use of the LoggerLevel::toLevel() function to obtain a LoggerLevel object.
i.e.,
$rootlogger->setLevel(LoggerLevel::DEBUG);
Should instead be:
$rootlogger->setLevel(LoggerLevel::toLevel(LoggerLevel::DEBUG));
(2) Here is a similar example to the one above, with a few differences:
uses rolling log files (max size of each log file is 100MB and at most 10 are kept)
uses a custom pattern for the log lines
fixes the setLevel bug
sets the log level at INFO
The code:
$rootlogger = Logger::getRootLogger();
$rootlogger->setLevel(LoggerLevel::toLevel(LoggerLevel::INFO));
$appender = new LoggerAppenderRollingFile("MyAppender");
$appender->setFile("custom_name.log", true);
$appender->setMaxBackupIndex(10);
$appender->setMaxFileSize("100MB");
$appenderlayout = new LoggerLayoutPattern();
$pattern = '%d{Y-m-d H:i:s} [%p] %c: %m (at %F line %L)%n';
$appenderlayout->setConversionPattern($pattern);
$appender->setLayout($appenderlayout);
$appender->activateOptions();
$rootlogger->removeAllAppenders();
$rootlogger->addAppender($appender);
$rootlogger->info("info");

Well its not my code, But here is the sample code and link to the site
require_once('log4php/Logger.php');
$rootlogger = Logger::getRootLogger();
$rootlogger->setLevel(LoggerLevel::DEBUG);
$appender = new LoggerAppenderFile("MyAppender");
$appender->setFile("mylogfile.log", true);
$appenderlayout = new LoggerLayoutTTCC();
$appender->setLayout($appenderlayout);
$appender->activateOptions();
$rootlogger->removeAllAppenders();
$rootlogger->addAppender($appender);
$rootlogger->info("info");
$rootlogger->error("error");
$rootlogger->debug("debug");
Actual Site Link
Credit goes to "AKJOL"

Related

How to close a QInputDialog with after a defined amount of time

I'm currently working on an application that run in the background and sometime create an input dialog for the user to answer. If the user doesn't interact, I'd like to close the dialog after 30 seconds. I made a QThread that act like a timer and the "finished" signal should close the dialog. I unfortunately cannot find a way to close it.
At this point I'm pretty much lost. I completely new to QThread and a beginner in PyQt5
Here is a simplified version of the code (we are inside a class running a UI):
def Myfunction(self,q):
# q : [q1,q2,q3]
self.popup = counter_thread()
self.popup.start()
self.dial = QInputDialog
self.popup.finished.connect(self.dial.close)
text, ok = self.dial.getText(self, 'Time to compute !', '%s %s %s = ?'%(q[0], q[2], q[1]))
#[...]
I tried ".close()" and others but i got this error message:
TypeError: close(self): first argument of unbound method must have type 'QWidget'
I did it in a separated function but got the same problem...
You cannot close it because the self.dial you created is just an alias (another reference) to a class, not an instance.
Also, getText() is a static function that internally creates the dialog instance, and you have no access to it.
While it is possible to get that dialog through some tricks (installing an event filter on the QApplication), there's no point in complicating things: instead of using the static function, create a full instance of QInputDialog.
def Myfunction(self,q):
# q : [q1,q2,q3]
self.popup = counter_thread()
self.dial = QInputDialog(self) # <- this is an instance!
self.dial.setInputMode(QInputDialog.TextInput)
self.dial.setWindowTitle('Time to compute !')
self.dial.setLabelText('%s %s %s = ?'%(q[0], q[2], q[1]))
self.popup.finished.connect(self.dial.reject)
self.popup.start()
if self.dial.exec():
text = self.dial.textValue()
Note that I started the thread just before showing the dialog, in the rare case it may return immediately, and also because, for the same reason, the signal should be connected before starting it.

Snowflake COPY INTO from JSON - ON_ERROR = CONTINUE - Weird Issue

I am trying to load JSON file from Staging area (S3) into Stage table using COPY INTO command.
Table:
create or replace TABLE stage_tableA (
RAW_JSON VARIANT NOT NULL
);
Copy Command:
copy into stage_tableA from #stgS3/filename_45.gz file_format = (format_name = 'file_json')
Got the below error when executing the above (sample provided)
SQL Error [100069] [22P02]: Error parsing JSON: document is too large, max size 16777216 bytes If you would like to continue loading
when an error is encountered, use other values such as 'SKIP_FILE' or
'CONTINUE' for the ON_ERROR option. For more information on loading
options, please run 'info loading_data' in a SQL client.
When I had put "ON_ERROR=CONTINUE" , records got partially loaded, i.e until the record with more than max size. But no records after the Error record was loaded.
Was "ON_ERROR=CONTINUE" supposed to skip only the record that has max size and load records before and after it ?
Yes, the ON_ERROR=CONTINUE skips the offending line and continues to load the rest of the file.
To help us provide more insight, can you answer the following:
How many records are in your file?
How many got loaded?
At what line was the error first encountered?
You can find this information using the COPY_HISTORY() table function
Try setting the option strip_outer_array = true for file format and attempt the loading again.
The considerations for loading large size semi-structured data are documented in the below article:
https://docs.snowflake.com/en/user-guide/semistructured-considerations.html
I partially agree with Chris. The ON_ERROR=CONTINUE option only helps if the there are in fact more than 1 JSON objects in the file. If it's 1 massive object then you would simply not get an error or the record loaded when using ON_ERROR=CONTINUE.
If you know your JSON payload is smaller than 16mb then definitely try the strip_outer_array = true. Also, if your JSON has a lot of nulls ("NULL") as values use the STRIP_NULL_VALUES = TRUE as this will slim your payload as well. Hope that helps.

Lego-EV3: How to fix EOFError when catching user-input via multiprocessing?

Currently, I am working with a EV3 lego robot that is controlled by several neurons. Now I want to modify the code (running on
python3) in such a way that one can change certain parameter values on the run via the shell (Ubuntu) in order to manipulate the robot's dynamics at any time (and for multiple times). Here is a schema of what I have achieved so far based on a short example code:
from multiprocessing import Process
from multiprocessing import SimpleQueue
import ev3dev.ev3 as ev3
class Neuron:
(definitions of class variables and update functions)
def check_input(queue):
while (True):
try:
new_para = str(input("Type 'parameter=value': "))
float(new_para[2:0]) # checking for float in input
var = new_para[0:2]
if (var == "k="): # change parameter k
queue.put(new_para)
elif (var == "g="): # change parameter g
queue.put(new_para)
else:
print("Error". Type 'k=...' or 'g=...')
queue.put(0) # put anything in queue
except (ValueError, EOFError):
print("New value is not a number. Try again!")
(some neuron-specific initializations)
queue = SimpleQueue()
check = Process(target=check_input, args=(queue,))
check.start()
while (True):
if (not queue.empty()):
cmd = queue.get()
var = cmd[0]
val = float(cmd[2:])
if (var == "k"):
Neuron.K = val
elif (var == "g"):
Neuron.g = val
(updating procedure for neurons, writing data to file)
Since I am new to multiprocessing there are certainly some mistakes concerning taking care of locking, efficiency and so on but the robot moves and input fields occur in the shell. However, the current problem is that it's actually impossible to make an input:
> python3 controller_multiprocess.py
> Type 'parameter=value': New value is not a number. Try again!
> Type 'parameter=value': New value is not a number. Try again!
> Type 'parameter=value': New value is not a number. Try again!
> ... (and so on)
I know that this behaviour is caused by putting the exception of EOFError due to the fact that this error occurs when the exception is removed (and the process crashes). Hence, the program just rushes through the try-loop here and assumes that no input (-> empty string) was made over and over again. Why does this happen? - when not called as a threaded procedure the program patiently waits for an input as expected. And how can one fix or bypass this issue so that changing parameters gets possible as wanted?
Thanks in advance!

Dymola Results of checkModel()

checkmodel([Some Model]) opens the GUI "Dymola Messages", tab "Translation" and displays Errors, Warnings, and Messages.
Does anyone know how to write these infos to a logfile or get them as kind of return value of checkModel(). All I've found in the documentation was, that checkModel() only returns a success-boolean. Are these infos saved temporarily somewhere?
Note, that I only want to apply checkModel() but not actually translating the code.
I finally found a solution at least for Dymola 2016 and newer, so if someone is interested - here it is (it is not very user-friendly, but it works):
The key-command is getLastError() which not only returns the last error (as one could think...), but all errors that are detected by checkModel() as well as the overall statistics.
All informations are sampled in one string, in which the last lines looks like:
"[...]
Local classes checked, checking <[Some Path]>
ERROR: 2 errors were found
WARNING: 13 warnings were issued
= false
"
Following operations will return the number of actual errors (for warnings it is more or less the same):
b = checkmodel([Some Model])
s = getLastError()
ind1 = Modelica.Utilities.Strings.findLast(s,"ERROR:")
ind2 = Modelica.Utilities.Strings.findLast(s," errors were found")
nErrors = Modelica.Utilities.Strings.substring(s,ind1+6,ind2) //6 = len(ERROR:)
nErrors = Modelica.Utilities.Strings.replace(nErrors," ","")
nErrors
= "2"
Note:
I used findLast as I know, that the lines of interest are at the very end of the string. So this is significantly faster than using find
This only works, if the line "ERROR: ...." actually exists. Otherwise, the substring call will throw an error.
Of course this could be done in less lines, but maybe this version is easier to read.
NOTE: This will only works with Dymola 2016 and newer. The return-string of getLastError is of a different structure in Dymola 2015 and older.
The following should handle it:
clearlog(); // To start fresh
Advanced.TranslationInCommandLog=true;
checkModel(...);
savelog(...);
This is mentioned in the Dymola User Manual Volume 1, section "Parameter studies by running Dymola a number of time in “batch mode”" on pg 630 or so.

Invalid operation result set is closed errorcode 4470 sqlstate null - DB2 data extract

I am running a very simple query and trying to extract the results to a text file. The entire query is essentially what is below, I am selecting everything from one single table with one piece of where criteria which is limiting the data to one month's worth. After it has extracted around 1.2 gig this error shows up. Is there any way that I can work around this other than extracting smaller date ranges? I am trying to pull a couple of years worth of data so if I can only get it a few days at a time it will take a lot of manual work.
I am currently using the free trial of a DB2 query tool - Razor SQL if that makes a difference, I can probably purchase different software if it would help. I am trying to get IBM's tool but for some reason it freezes during the download so I am still working on that. I have searched about this error but everything I see seems much more complex than what I am doing and I can't tell if it applies or not. Thanks in advance.
select *
from MyTable
where date_col between date '2014-01-01' and date '2014-01-31'
I stumbled at this error too, found out it is related to db2jcc.jar (type 4) driver.
Excerpt: If there are no items in the result set left (or to begin with), the Result set is closed automatically and therefore the Exception. Suggestion is to handle it in the application, perhaps in my case, I started checking if(rs.next()) but otherwise, there is a work around. Check out the source link below for how you can set some properties to Data source and avoid exception.
Source :
"Invalid operation: result set is closed" error with Data Server Driver for JDBC
In my case, i missed some properties in WAS, after add allowNextOnExhaustedResultSet the issue is fixed.
1.Log in to the WebSphere Application Server administration console.
2.Select Resources > JDBC > Data sources > Application Center DataSource name > Custom properties and click New.
3.In the Name field, enter allowNextOnExhaustedResultSet.
4.In the Value field, type 1.
5.Change the type to java.lang.Integer.
6.Click OK.
Sometimes you need also check whether resultSetHoldability properties exists. Details refer to here.
I encountered this failure also when ugrading from JDBC Type 2 driver (db2java.zip) JDBC type 4 driver (db2jcc4.jar)
Statement statement = results.getStatement();
if (statement != null)
{
connection = statement.getConnection(); // ** failed here
statement.close();
}
Solution was to check if the statement is closed or not as follows.
Changed to:
Statement statement = results.getStatement();
if (statement != null && !statement.isClosed()) {
{
connection = statement.getConnection();
statement.close();
}
Creating property bellow with type Integer it's worked for me:
allowNextOnExhaustedResultSet:
I had the same issue on WAS 7 so i had to add and change few this on Admin Console.
This TeamWorksRuntimeException exception should be fixed by applying APAR JR50863 which is available on top of BPM V8.5.5 or included on BPM V8.5 refresh pack 6.
For the case that the APAR does not solve the problem, try following workaround:
Log in to the WebSphere Application Server admin console
Select Resources > JDBC > Data sources > DataSource name (TeamWorksDB) > Custom properties and click New
In the Name field, enter downgradeHoldCursorsUnderXa
In the Value field, type true
Change the type to java.lang.Boolean
Click OK to save your changes
Select custom property resultSetHoldability
In the Value field, type 1
Click OK to save your changes
Source of the Answer : https://developer.ibm.com/answers/questions/194821/invalid-operation-result-set-is-closed-errorcode-4/
Restarting the app may fix the problem if connection pool lost session to Db2. If using Tomcat then connection pool property of 'testonBorrow' may reestablish the connection to Db2.